Introduction to Mathematica

Part I		Getting Started			Part V 		Algebraic Calculations	  
	Part II		Getting Help				Part VI	Functions
	Part III  	Numerical Calculations		Part VII	Solving Equations  
	Part IV 	Multi-dimensional Objects

Department of Economics
Iowa State University

Part I      Getting Started

Main Menu  Part: I  II  III  IV  V  VI  VII

Contents

1. What is Mathematica?			10. Referencing Previous Commands
		2. Starting Mathematica			11. Using BasicInput Palette
		3. Typing in the Notebook			12. /. Command
		4. Cell & Group				13. Suppressing and Displaying Output
		5. Input Commands				14. Decimal Arithmetic and Approximation
		6. Graphs					15. Comments between Commands
		7. Basic Arithmetic				16. Saving & Opening a Notebook
		8. Defining Variables				17. Printing
		9. Variables					18. Completing a Session

Part I. Getting Started

Main Menu  Part: I  II  III  IV  V  VI  VII

1. What is Mathematica ?
Mathematica is a versatile, powerful application package for doing mathematics and publishing mathematical results. 
It runs on most popular workstation operating systems, including Microsoft Windows, Apple Macintosh OS, Linux, and Unix-based systems.  
Mathematica is used by scientists and engineers in disciplines ranging from astronomy to zoology; typical applications include computational number theory, ecosystem modeling, financial derivatives pricing, economic optimization, quantum computation, statistical analysis, and more.

Part I. Getting Started

Main Menu  Part: I  II  III  IV  V  VI  VII

2. Starting Mathematica
If you use your computer via a graphical interface such as Windows, you double-click the Mathematica icon to start Mathematica.  When Mathematica starts up, it usually takes you straight into the notebook interface; a separate window into which Mathematica commands are typed.  
You can use the standard editing features of your graphical interface to prepare your input, which may go on for several lines. For example, Control-c, Control-x, and Control-v work for copy, cut, and paste as with other windows software.  One can go back to an old command, edit it, and then rerun it; convenient if one makes a typo in a long command. Both input and output can produce Greek letters and other special symbols. 
To execute a command in Windows, you need to hold down the Shift key as well as pressing Enter ⇧|⌤.
Just pressing Enter ⌤ allows you to continue entering your command on the next line but does not execute it.
In this tutorial, you should execute the commands in each cell before proceeding to the next cell.  By doing this you will ensure that later commands are based on the execution of assumed earlier commands.

Part I. Getting Started

Main Menu  Part: I  II  III  IV  V  VI  VII

3. Typing in the Notebook

Click on the notebook to make it active.  Then type an expression in the notebook.  For example, consider the expression 2*3.  We could enter it as 2*3 or 2 3.

If you hold down the Shift key and then press enter ⇧|⌤, Mathematica will evaluate the expression. 
After you send Mathematica input from your notebook, Mathematica will label your input with In[n]:=. It labels the corresponding output Out[n]=.  When you type an expression such 2 3, and then end the input with ⇧|⌤, Mathematica processes the input, adds the input label In[1]:=, and gives the output. Try executing the cell below by putting the cursor in it and then pressing ⇧|⌤.

2 3

As an alternative, try Factor[x^2+x-6], where ^ is used to denote an exponent or x squared on this case.

Factor[x^2+x-6]

Part I. Getting Started

Main Menu  Part: I  II  III  IV  V  VI  VII

4. Cell & Group
Notice the brackets along the right margin of the notebook window.  Each input and output gets its own cell, whose scope if determined by the leftmost bracket directly across from the respective input or output text.  Cells containing input are called input cells.  Cell containing output are called output cells.  The brackets delimiting the cells are called cell brackets.  Each input-output pair is in turn grouped with a larger bracket immediately to the right of the cell brackets.  These brackets may in turn be grouped together by a still larger bracket , and so on.  These extra brackets are called grouping brackets.  
If you position the tip of the cursor arrow anywhere on a grouping bracket and double click, the group determined by that bracket will close.  Try this by double clicking on the large braket to the left of this group of cells.  If the bracket covers an input-output pair, the output will be hidden.  You can double click again to open the bracket.  If you want to delete a cell, you can click on the bracket associated with the cell and then press the delete key. Try out yourself!

Factor[x^2+x-6]

Part I. Getting Started

Main Menu  Part: I  II  III  IV  V  VI  VII

5. Input Commands
If two input commands are placed in the same input cell, they will both execute when you hold down ⇧|⌤.  Consider the following example.

a=1; b=-6;c=2;
Plot[a x^2-b x+c,{x,-6,6}]

The plot command typically has two arguments, the expression to plot, and an expression in brackets listing the variable on the horizaontal axis and the left and right most points in the domain. More arguments and options can be added for more detailed plots.  For more information about Plot, see the Help Menu.

Part I. Getting Started

Main Menu  Part: I  II  III  IV  V  VI  VII

6. Graphs
One can create more complicated and professional looking graphs using various options available on Mathematica commands.

Plot[(x^2)-6 x+2,{x,-6,6},AxesStyle->{RGBColor[0.8`,0.2`,0.1`],Thickness[0.011`]},PlotStyle->{RGBColor[0.2`,0.3`,0.8`],Thickness[0.011`]},BaseStyle->{FontColor->RGBColor[0.1`,0.1`,0.1`],FontWeight->"Bold",FontFamily->"Times",FontSize->14},PlotLabel->Style["Graph of a Polynomial",FontSize->18,FontColor->RGBColor[0.1`,0.2`,0.3`]]]

Or one can create 3D plots and contour plots.

Plot3D[100-2 (x^2)-(y^2),{x,-10,10},{y,-10,10},AxesLabel->{"x","y","f(x,y)"},ViewPoint->{-8,5,0},ColorFunction->Hue]
ContourPlot[100-2 (x^2)-(y^2),{x,-10,10},{y,-10,10},ColorFunction->Hue]

One can use the cursor to grag teh corner of a graph or plot to make if larger or smaller.
One can also create more complicated graphs and plots by overlaying one plot on another.

Clear[x,y];
c=0.9`;
surface=Plot3D[((((x^2) (y^2)) (1+(y^2)))/(1+(x^2))),{x,0,2},{y,0,2},DisplayFunction->Identity,ColorFunction->Hue];levelset=Plot3D[c,{x,0,2},{y,0,2},DisplayFunction->Identity];
Show[surface,levelset,AxesLabel->{"x","y","f(x,y)"},ViewPoint->{3.296`,0,0.764`},DisplayFunction->$DisplayFunction]

Part I. Getting Started

Main Menu  Part: I  II  III  IV  V  VI  VII

7. Basic Arithmetic
+		add
-		subtract
*		multiply (Or as an alternative, you can multiply two numbers by leaving a space between them.)
/		divide
^		exponent
Arithmetic expressions can be grouped using parentheses to make clear the order of evaluation.  For example

(3 + 4) ^ 2 - 2 (3 + 1)

Part I. Getting Started

Main Menu  Part: I  II  III  IV  V  VI  VII

8. Defining Variables
When you do long calculations, it is often convenient to give names to intermediate results. Just as in standard mathematics, or in other computer languages, you can do this by introducing named variables.   Values are given to variables using assignemnt statements of the form varname = expression where expression is a mathematical formula or equation.  For example this sets the value of the variable y to be 7.

y=7

Whenever x appears, Mathematica now replaces it with the value 7.

The values you assign to variables are permanent. Once you have assigned a value to a particular variable, the value will be kept until you explicitly remove it. This can be done by assigning a null value to the variable or by using the Clear command.  The assigned value will disappear if you start a whole new Mathematica session.  Forgetting about definitions is probably the single most common cause of mistakes when using Mathematica

y^2
Clear[y];
y^2

When we clear the variable y, it no longer has the expression (value) 7 assigned to it.
We can change the value of y using a new assignment statement.

y=7+5

This creates a new variable z.

z=y+4

And this creates the variable z1.

z1=y*z

We can also use more complicated expressions on the right hand side of the assignment statement.

z2 = 3x^2-2^x+sqrt[x]/Exp[x]

We can then determine the value of z4 for different values of x.  For example, consider the value of z2 when x = 4.

x=4
z2

Part I. Getting Started

Main Menu  Part: I  II  III  IV  V  VI  VII

9. Variables
Variables can have almost any names. There is no limit on the length of their names. One constraint, however, is that variable names can never start with numbers. For example, x3 could be a variable, but 3x means 3*x.  Mathematica uses both upper- and lower-case letters. There is a convention that built-in Mathematica objects always have names starting with upper-case (capital) letters.  Therefore to avoid confusion, always choose names for variables that start with lower-case letters.

Clear[x,w];
x= 3
w
x=.
x
w=4

A variable that has no value assigned to it will appear in output as the variable name.

Part I. Getting Started

Main Menu  Part: I  II  III  IV  V  VI  VII

10. Referencing Previous Commands

The result from the previous command can be referenced by the percent sign %, the second previous result by two percent signs, %%, and so on, and the result from output line n by %n,  e.g.

12
%+8

Part I. Getting Started

Main Menu  Part: I  II  III  IV  V  VI  VII

11. Using BasicInput Palette
One can also enter commands into a Mathematica notebook using the input palette.  If it is not visible on the screen, you can go the file menu, select palettes, and then choose BasicInput. The palette gives a way to simplify the entry of a number of useful commands. Open BasicInput Palette now!
For example one can enter 6 squared as either 6^2 or by choosing the button in the upper left hand corner of the palette (◼^□). Type a 6 into the notebook, highlight it and then click on the (◼^□) button. The cell will now look like this (6^□). You can then type a 2 and it will be placed in the exponent box as follows (6^2). 
Alternatively one could choose the (◼^□)button and type the six in the first box and then use the ⇥ key to put the 2 in the exponent box.

(6^2)

BasicInput Pallette works equally well with more complicated functions such as integrals.  For example consider

Clear[x];
Print["This is an indefinite integral"]
Int1=∫(3x^2-5 x + 2)\[DifferentialD]x
Print["This is an indefinite integral evaluated from 0 to 2"]
(Int1/.x->2)-(Int1/.x->0)
Print["This is a definite integral evaluated from 0 to 2"]
(∫_0^2)(3 x^2-5 x+2)\[DifferentialD]x

We can evaluate the indefinite integral and then substitute for x, or evaluate the definite integral.  The /. command allows one to replace a variable with a specific value or expression.  For example in the expression (Int1 /. x->2) is replaced by 2, in this case replacing x in 2x - ((5(x^2))/2)+ (x^3) with 2.

Part I. Getting Started

Main Menu  Part: I  II  III  IV  V  VI  VII

12. /. Command
The /. command is an abbreviation for the ReplaceAll command which has the form  expr /. rules and applies a rule or list of rules in an attempt to transform each subpart of an expression.  For example, y /. x -> a^2 replaces x with a2 in the expression for y.  An example follows.  This will be discussed in more detail later.

Clear[x,y,a];
Print["This is an equation for y"];
y=x+2
Print["This is an equation for y replacing x with a^2"];
y /. x->a^2

Print["This is an equation assigning 4 to a"];
a=4
Print["This is an equation for y replacing x with a^2"];
y /. x->a^2

Part I. Getting Started

Main Menu  Part: I  II  III  IV  V  VI  VII

13. Suppressing and Displaying Output
Almost all Mathematica commands produce some type of output when you hold down ⇧|⌤.  Sometimes it is not necessary to see the results of a particular command.  For example, one might want to assign the variable a the value of 4 and then use it in a computation.  There may be no need to see this assignment in the output cell.  If a command ends with a semicolon (;), it will be executed but no output will be produced.  Consider the following example.

Clear[x,y,a];
Print["This is an equation for y"];
y=x+z

Print["This assigns a value to z and then evaluates y"];
z=6;
y

Print["This assigns a value to a and then evaluates y"];
a=4;
y/.{x->5,z->a}

Part I. Getting Started

Main Menu  Part: I  II  III  IV  V  VI  VII

14. Decimal Arithmetic and Approximation
By default, Mathematica produces exact results.  For example, Mathematica gives an exact result for (2^50), even though it has 16 decimal digits.

2^50

You can tell Mathematica to give you an approximate numerical result, just as a calculator would, by ending your input with //N. The N stands for "numerical". It must be a capital to get an approximate numerical value, use expr //N.  By default, the approximation will have six significant digits.

Clear[v1, v2, v3, v4, v5];
v1=2^50

v2=2^50//N

If you use a decimal point, Mathematica assumes the number is accurate only to a fixed number of decimal places. By placing a decimal after an integer, you can force Mathematica to give you approximate results. When Mathematica prints out numbers, it usually tries to give them in a form that will be as easy as possible to read.

v3=2.^50

One can also use the N command with arguments to specify a specific number of significant digits.  For example N[v1,8] would create an eight digit approximation to the variable v1.

v4=N[2^50,8]

N[2^50,18]

N[v1,25]

Please note that unless numbers in expr are exact, or of sufficiently high precision, N command may not be able to give results with n-digit precision. for example,

N[v2,10]

v2, after first approximation, is no long of "sufficiently high precision", so mathematica could not give n-digit precision again. While in the following example, v5, after first approximation, is still of "sufficiently high precision", Mathematica can futher give n-digit approximation.

v5=N[2^50,18]

N[v5,8]

Part I. Getting Started

Main Menu  Part: I  II  III  IV  V  VI  VII

15. Comments between Commands
Mathematica allows you to insert comments betweent commands. The syntax for comments is 
		(* comments go here *)
Comments will not show up in the Output. Notice the difference between a comment and the Print command. For example:

Clear[x, y, z];
(* This is a comment: Assign the expression x^2+5y to z *)
Print["This is a 'Print' Command: Assigns the expression x^2+5y to z"];
z=x^2+5 y

Part I. Getting Started

Main Menu  Part: I  II  III  IV  V  VI  VII

16. Saving & Opening a Notebook
To save a notebook to a disk, click on the File menu bar.  You will see a typical Windows menu.  Select Save or Save as from the File menu.  Navigate to the appropriate place on the hard drive or other medium, give the notebook a name, and then click ASave@.  Once the notebook has a name, the Save command will save it with the same name in the same place from which it was opened.
To open a saved notebook, click on the File menu and select Open.  Mathematica saves files with the extension A.nb@.

Part I. Getting Started

Main Menu  Part: I  II  III  IV  V  VI  VII

17. Printing
The contents of a notebook can be printed from the File menu.  This menu contains items three main items directly related to printing, each with subheadings or options:
Printing Settings		Page Setup
				Printing Options
				Headers and Footers
Print  B  which brings up a Print dialog box allowing the selection of the range of pages to print, the magnification, page size or orientation, and where (printer or file) to send the output.
Print Selection  B  which prints the currently selected text or graphic.  If a graphic object is selected, it can be resized before printing by dragging the black boxes, or handles, along the frame that is drawn around the graphic.

Part I. Getting Started

Main Menu  Part: I  II  III  IV  V  VI  VII

18. Completing a Session
To close a given notebook, choose Close from the File menu or click in the upper right hand box of notebook screen.  You will be prompted as to whether to save the notebook if it has been modified since the last time it was saved.
To exit Mathematica, select Exit from the File menu.

Part II      Getting Help

Main Menu  Part: I  II  III  IV  V  VI  VII

Contents

1. Use of the Question Mark		3. More Help
		2. Wild Card Character			4. Introduction to Mathematica from Wolfram Research, Inc.

Part II. Getting Help

Main Menu  Part: I  II  III  IV  V  VI  VII

1. Use of the Question Mark

On-line help on Mathematica functions and other objects can be obtained by typing a question mark at the start of a line followed by the name of the object, e.g. to obtain information on Pi.

?Pi

More information is obtained with a double question mark, e.g. ??Plot gives a list of the (many) options to the plot command as well as the syntax of the command.

??Plot

Part II. Getting Help

Main Menu  Part: I  II  III  IV  V  VI  VII

2. Wild Card Character

You can also use wild card characters, such as * which matches any sequence of alphanumeric characters. For example ?Plot* give a list of commands which begin with Plot.

?Plot*

Part II. Getting Help

Main Menu  Part: I  II  III  IV  V  VI  VII

3. More Help

More general help can be obtained on the menu bar by clicking on Help.  This makes available a library of resources including a help browser, a tutorial, a section on getting started, demos, and the complete text of the Mathematica book.  When you enter a word in the Go To box and hit enter, a description of the command and examples will be provided.

Part II. Getting Help

Main Menu  Part: I  II  III  IV  V  VI  VII

4. "Introduction to Mathematica" from Wolfram Research, Inc.

Here is a module entitled "Introduction to Mathematica" from Wolfram Research, Inc.  It is a useful way to practice your knowlege of Mathematica and learn new commands.

Part III      Numerical Calculations

Main Menu  Part: I  II  III  IV  V  VI  VII

Contents

1. Built-in Mathematical Functions		4. Lists - Working with lists	
		2. Lists - Defining lists				5. Lists - More examples
		3. Lists - Extracting values from lists		6. Tables

Part III. Numerical Calculations

Main Menu  Part: I  II  III  IV  V  VI  VII

1. Build-in Mathematical Functions

Mathematica includes a very large collection of mathematical functions.  Some of the most common are contained in the following table.

	Table 1  Mathematical Functions
Sqrt[x]				square root of x
Exp[x]				exponential ((e^x))
Log[x]				natural logarithm of x
Log[b,x]			base b logarithm of x
Sin[x], Cos[x], Tan[x]	trigonometric functions (with x in radians)
Abs[x]				absolute value of x
Round[x]			closest integer to x
Random[ ]			pseudorandom number between 0 and 1
Max[x,y, ...], Min[x,y, ...]	maximum and minimum of x, y, ...
FactorInteger[n]		prime factors of n
IntergerPart[x]			integer part of x
FractionalPart[x]		fractional part of x
Mod[k, n]			k modulo n (remainder from dividing k by n)
n!				factorial n(B1)(B2)...1
Binomial[n,m]		binomial coefficient 
Gamma[z]			Euler gamma function
I				i
Infinity				∞
Pi				π
E			        e=2.14159...
Degree 			degrees to radians conversion factor

You can get descriptions of all functions directly from the Mathematica kernel using ?Function.  For example:

?Sqrt

Clicking on more will bring up the Help Browser entry on Sqrt.
The arguments of all Mathematica commands and functions are enclosed in square brackets ( [ ] ).  Parentheses are for grouping terms, square brackets are for denoting arguments.  We will see later than curly brackets ( { } ) are used for denoting lists of items.
As mentioned previously, all Mathematica functions begin with an upper case letter, if they involve two words, such as FactorTerms, the second term also begins with an uppercase letter.  For example:

Clear[x,y];
y=7x^3-21x^2+91x-14;
y
FactorTerms[y]

Part III. Numerical Calculations

Main Menu  Part: I  II  III  IV  V  VI  VII

2. Lists - Defining lists

To denote a list of items, use curly brackets.
You can perform functions on the whole list instead of having to repeat the calculation several times.  The following example demonstrates how create a list and then make calculations using it.

Clear[x,y,z,a];
x={1,2,3,4,5};
Print["This is x ",  x];

a=3;
z=a *x;
Print["This is ax ", z];

y=z^2+3;
Print["This is y = (ax)^2+3  ", y];

Part III. Numerical Calculations

Main Menu  Part: I  II  III  IV  V  VI  VII

3. Lists - Extracting values from lists

To extract a particular value of a list, use Part[list, I] or list[[ j ]] or list[[{i,j}]].  This also works with two dimensional objects which will be discussed later.

Clear[x,w,z, p25];
x={1,2,3,4,5};
Print["This is x ",  x];
Print["This is the fourth element of x"];
Part[x,4]
w={2,4,8,16,32};
Print["This is w ",  w];
Print["These are the second and fifth elements of w"];
p25=w[[{2,5}]];
p25

Print["This is z, which is x multiplied term by term by w"];
z=x*w;
z
Print["This is the fourth element of z, ", z[[4]] ];

Part III. Numerical Calculations

Main Menu  Part: I  II  III  IV  V  VI  VII

4. Lists - Join, Union, Intersection, and Flatten

Join[a, b, c, ...] creates a single list out of them and Union[a, b, c, ...] creates a sorted list with duplicated elements removed.  Intersection [a, b, c, ....] creates the intersection of the lists.  Join and Union can take any number of arguments, each of which should be a list. For example:

Clear[a, b, d, e, e1];
Print["This is a"];
a={1,2,3,4}
Print["This is b"];
b={1,4,9,16}
Print["This is the joining of a and b"];
d=Join[a,b]
Print["This is the union of a and b"];
e=Union[a,b]
Print["This is the intersection of a and b"];
e1=Intersection[a,b]

Lists can be nested in that an element of a list can be another list.  For example

Clear[a, b, c, f, f1]
a={1,2,3,4};
Print["This is a,  ", a];
b={1,4,9,16};
Print["This is b,  ", b];
Print["This is c which is a nested list made from b and 100"];
c={b,100}
Print["This is f which is a nested list made from a, b, and c"];
f={a,b,c}
Print["This is f1 which is a nested list made from f, 10, and 100"];
f1={a,b,c,10,100}

Flatten[list] removes inner brackets from nested lists, e.g.

Print["This flattens f"];
Flatten[f]
Print["This flattens f1"];
Flatten[f1]

Part III. Numerical Calculations

Main Menu  Part: I  II  III  IV  V  VI  VII

5. Lists - More examples

We can create new objects in a variety of ways by joining, creating unions and intersections, and extracting parts.

Clear[a,b, c,f, f1,g, g1, g2, h1, h2, α1, α2,β1]
a={1,2,3,4};
b={1,4,9,16};
c={b,100}
f={a,b,c}
f1={a,b,c,10,100}
g=Join[a,c];
Print["This is the joining of a and c,  ", g];
h=Union[a,c];
Print["This is the union of a and c,  ", h];
g1=Join[a,f1];
Print["This is the joining of a and f1,  ", g1];
h1=Union[a,f1];
Print["This is the union of a and f1,  ", h1]
g2=Join[a,c,f1];
Print["This is the joining of a, c and f1,  ", g2];
h2=Union[a,c,f1];
Print["This is the union of a, c and f1,  ", h2]
α1=h2[[3]];
Print["This is the third element of the union of a, c and f1, ", α1]
α2=h2[[8]];
Print["This is the eighth element of the union of a, c and f1, ", α2]
β1=Intersection[c,f];
Print["This is the intersection of c and f ", β1]

Part III. Numerical Calculations

Main Menu  Part: I  II  III  IV  V  VI  VII

6. Tables

Mathematica provides the Table command as an easy way to generate lists.  The format for Table is Table[expr, iterator] which generates a list of expr. For example:

Table[n^3,{n,1,3}]

where n increments from 1 to 3 in increments of 1.
The list specifies the variable that increments as the list is created, the first number indicates the first value for n, the second number the last value, and the last number the increment.  By default, the increment is one.  Consider the following two examples.

Clear[x, t1];
Print["This is table of log[x] where x goes from 1 to 10 by 2s"];
t1=Table[Log[x],{x,1,10,2}]
N[t1]

Notice that Mathematica reports exact values for logs.  We use the numeric command (N) to get decimal equivalents.

Clear[y];
Print["This is table of the absolute value of y goes from -12 to 12 by 3s"];
Table[Abs[y],{y,-12,12,3}]

Table[expr, {n}] executes expr n times, as in the following example where Random[ ] generates a uniform random number between 0 and 1.

RandomReal[{0,1},5]

Part IV. Multi-dimensional Objects

Main Menu  Part: I  II  III  IV  V  VI  VII

Contents

1. Vectors and Matrices			3. Repetitive Calculations
		2. Matrix Operations

Part IV. Multi-dimensional Objects

Main Menu  Part: I  II  III  IV  V  VI  VII

1. Vectors and Matrices

A vector in Mathematica is simply a one dimensional list.  A matrix is a list of lists.  For example we might define a as {1,3,5} and b as {2,4,6}.  These can be added to obtain c = a+b.

Clear[a, b, c]
Print["These are the vectors a and b"];
a = {1,3,5,7}
b={2,4,6,8}
Print["This is the vector c =  a + b"];
c=a+b

We can enter a matrix in several ways.  One way is to create a list of lists.  This will be displayed as a nested list.  To see it as a matrix we need to use the MatrixForm command.  Consider entering the following matrix.

Clear[mat1];
Print["This is the matrix 'mat1' in list form"];
mat1={{2,4,6,8},{1,3,5,7},{2,4,8,16},{3,9,27,81}}
Print["This is the matrix 'mat1' in matrix form"];
MatrixForm[mat1]

Print["This is the vector 'a' in matrix form"];
MatrixForm[a]

Vectors can be listed as column vectors using MatrixForm but they remain one dimensional lists, not matrices.  To create a row vector, one would create a nested list with one list.

Clear[aprime];
Print["This is a row vector 'aprime' "];
aprime={{1,3,5,7}}
MatrixForm[aprime]

Compare this to the output from the following which is not a matrix but a list written as a row.

Clear[w];
Print["This is the list 'w' which will be written in row form."];
w={1,3,5,7}
Print["This is also the list 'w' (not a matrix) written as if it were a matrix with one column."];
MatrixForm[w]

The transpose of a matrix is obtained using the Transpose command.

Print["This is the transpose of 'mat1' "];
MatrixForm[Transpose[mat1]]
Print["This is the transpose of 'aprime' "];
MatrixForm[Transpose[aprime]]

Transpose is not defined for the vector 'a' as it is a one dimensional list, not a row vector.

Part IV. Multi-dimensional Objects

Main Menu  Part: I  II  III  IV  V  VI  VII

2. Matrix Operations

To multiply two vectors (create the dot product), we use a period between the two vectors as in c1 = a.b.  We can also multiply vectors by matrices.  Mathematica will decide how to configure the vector for proper multiplication.

Clear[a, b, c1, mat1, am, am1];
a = {1,3,5,7}
b={2,4,6,8}
mat1={{2,4,6,8},{1,3,5,7},{2,4,8,16},{3,9,27,81}}
Print["This is the dot product of 'a' and 'b' "];
c1=a.b
Print["This is the product of 'a' and 'mat1' "];
am=a.mat1
Print["This is the product of 'mat1' and 'a' "];
am1=mat1.a

If a vector is defined as a one-dimensional matrix, the proper order must be maintained to assure compatibility.

Clear[apm]; Print["This is the product of 'aprime' and 'mat1' "];
apm=aprime.mat1

This multiplication is compatible because we are premultiplying a 4x4 matrix by the 1x4 vector aprime.  If we were to post multiple the matrix mat1 by the row vector aprime, we would get an error message.

Clear[apm1]; Print["This is the product of 'mat1' and 'aprime'  "];
apm1=mat1.aprime

As you can see we get an error message about incompatible forms of the two objects being multiplied.  We can post muiltiply mat1 by the transpose of aprime (which is a column vector).

Clear[apm2]; Print["This is the product of 'mat1' and the transpose of 'aprime'"];
apm2=mat1.Transpose[aprime]//MatrixForm

If we performed this mulitplication and did not specify that the output appear in MatrixForm, we would obtain a list of lists.

Print["This is the product of 'mat1' and the transpose of 'aprime' written in  a list of lists form"];
apm2=mat1.Transpose[aprime]

Part IV. Multi-dimensional Objects

Main Menu  Part: I  II  III  IV  V  VI  VII

3. Repetitive Calculations

To perform repetitive operations in another way, use the Do function, which works like an iterative do loop in many programming languages. The syntax is as follows.
	Do[expr, {I, imax}] will evaluate expr with I running from 1 to imax.
	Do[expr, {I, imin, imax, di}] will evaluate expr with I running from imin to imax in steps of di

Clear[total, i];Print["This uses the Do command to create a total of the integers from one to five"];
total=0
Do[total=total+i, {i,1,5}]
total
Print["This uses the Do command to create a total of the squares of the integrers running from 0 to fifteen in steps of three"];
Do[total=total+i^2, {i, 0, 15,3}] 
total

The output from the commands generated by Do is not printed by default.  To obtain the results of individual steps, the Print command must be used.

Clear[a,k,n];
n=7;
a[0] = 1;
a[1] = 1;
Print["These are the Fibonacci numbers"]
Print[a[0]];
Print[a[1]];
 Do [ Print[a[k] = a[k-1] + a[k-2]],{k, 2, n}  ]

Part V      Algebraic Calculations

Main Menu  Part: I  II  III  IV  V  VI  VII

Contents

1. Symbolic Computation			3. A List of Algebraic Functions
		2. Working with Symbolic Expressions	4. Using the Postfix (//) Operator

Part V. Algebraic Calculations

Main Menu  Part: I  II  III  IV  V  VI  VII

1. Symbolic Computation

Mathematica can do symbolic computations using the same operators as in numerical calculations.   For example, it will combine terms as follows

Clear[x]; 
3 x^2+4 x-8 x^2

Part V. Algebraic Calculations

Main Menu  Part: I  II  III  IV  V  VI  VII

2. Working with Symbolic Expressions

There are often many different ways to write the same algebraic expression. Mathematica provides a large collection of functions for converting between different forms of algebraic expressions.  Two common functions for  transforming algebraic expressions are Expand and Factor.

Expand gives the "expanded form", with products and powers multiplied out.

Expand[(x-2)^2]

Factor recovers the original form.

Factor[%]

The function Simplify attempts to find the simplest form of an expression by using standard algebraic transformations.  Here are some examples.

Clear[x, y, t1, t2, t3, t4, t5]; Print["This is a rather complex function"];
t1=((x+2)^2*(x-1)(y+2))/(x^2-2x+1) +x^2+2x-3
Print["This expands the function"];
t2=Expand[t1]
Print["This puts it over a common denominator"];
t3=Together[t2]
Print["This simplifies the function"];
t4=Simplify[t3]

The function FullSimplify tries to find the simplest form of an expression by using a larger range of algebraic transformations than included in the Simplify function.  The result may or may not seem simpler than that obtained with Simplify.

Print["This simplifies the function more fully"];
t5=FullSimplify[t4]

Part V. Algebraic Calculations

Main Menu  Part: I  II  III  IV  V  VI  VII

3. A List of Algebraic Functions

Table 2  Algebraic Functions
Expand[expr]			expands out products and positive integer powers in expr. 
Factor[poly]			factors a polynomial over the integers. 
Simplify[expr]			performs a sequence of algebraic transformations on expr, and returns the simplest form it finds. 
FullSimplify[expr]		tries a wide range of transformations on expr involving elementary and special functions, and returns the simplest form it finds. 
ExpandAll[expr]		apply Exp everywhere (not just to products and powers)
Together[expr]			put all terms over a common denominator
Apart[expr]			separate into terms with separate denominators
Cancel[expr]			cancel common factors between numerators and denominators
Collect[expr, x]			group together powers of x
FactorTerms[expr, x]		pull out factors that do not depend on x
TrigExpand[expr]		expand trig expressions into a sum of terms
TrigFactor[expr]		factor trig expressions into products of terms
TrigToExp[expr]		convert trig functions to exponentials
ExptoTrig[expr]		convert exponentials to trig functions
Coefficient[expr, form]	coefficient of form in expr
Exponent[expr, form]		maximum power of form in expr
Part[expr, n] or expr[[n]]	nth term of expr
Numerator[expr]		numerator of expr
Denominator[expr]		denominator of expr
Short[expr, n]			show an n-line outline of expr (used for particularly long expressions)

Part V. Algebraic Calculations

Main Menu  Part: I  II  III  IV  V  VI  VII

4. Using the Postfix(//) Operator

When a command has only one argument, we may apply it to an expression using the // operator.

Clear[x,t1,t2]
Print["This uses the '//' operator to find the decial equivalent of a number"];
x=Log[4];
t1=Expand[(x-2)^2]
t2=t1//N

Clear[y,x,t1,t2]
Print["This uses the '//' operator to convert an exact polynomial to one in numeric form"];
y=(x+(4/3)x-2)^2
t1=Expand[y]
t2=t1//N

Part VI     Functions

Main Menu  Part: I  II  III  IV  V  VI  VII

Contents

1. Defining Functions with Delayed Assignment   
 		2. Differentiating between Functions and Ordinary Expressions
		3. Delayed versus Immediate Assignment
		4. Functions Involving Variables and Parameters
		5. More Function Examples
		6. Transformations Involving Functions

Part VI. Functions

Main Menu  Part: I  II  III  IV  V  VI  VII

1. Defining Functions with Delayed Assignment

There are many built-in functions in Mathematica, but it is often very useful to be able to create specialzed functions for a given problem.  The syntax for defining a function is
		f[x_ ] := expression involving x
The x in the expression f[x_ ] is a dummy variable.  The _ (referred to as Ablank@) on the left-hand side is important; it means that we can replace x with any value or expression, i.e., the argument when called can be named anything, not necessarily x. Secondly, the use of :=, rather than =, which means that the assignment is delayed until the function is called. In the present, the use of  :=, rather than =, means that the assignment of the expression on the right hand side is delayed until the function is actually called.  Consider, for example, a function defined as (x^2) +5.  We first clear the values of the function f and the argument x.  Then we define the function.

Clear[f,x];
f[x_]:=x^2+5

No output occurs because Mathematica is holding the definition in reserve for evaluation at a later time. If we call the function and replace x with the number 4 we obtain

f[4]

Similarly for other numbers or expressions.

Clear [f,x,y,t]
f[x_]:=x^2+5
f[x]
f[3]
f[y]
f[t+2]
f[y+t]//Expand

We can also define a function with parameters in the expression on the right hand side.  The values of these parameters can be changed, resulting in a different form for the function.  Define the function to be  a(x^2)+ bx + c.  Define values for the parameters, display the function, and then evaluate it at x = 4 and x = 2.

Clear[f,a,b,c,x];
a=1;
b=-4;
c=2;
Print["These are the initial parameters a = ",a,"  b = ", b, " and c = ",c];
Print["This is the equation representing the function"];
f[x_]:=a*x^2+b*x+c
f[x]
Print["This is the function f[x] evaluated at x = 4"];
f[4]
Print["This is the function f[x] evaluated at x = 2"];
f[2]

Notice that we must call the function with the argument x to have it displayed.  If we were to call the function with the argument t, we would obtain

f[t]

We can change the parameters using assignment statements.  For example, change the parameters to a = 1,  b = -2 and c = 4.

Clear[x];
a=1;b=-2;c=4;
Print["These are new values for the parameters a = ",a,"  b = ",b," and c = ",c];

If we now call the function, the new values for the parameters,a, b, and c will assigned when it  is called, yielding different results from previously.

Print["This is the equation representing the function using the new parameters"];
f[x]
Print["This is the function f[x] evaluated at x = 4"];
f[4]
Print["This is the function f[x] evaluated at x = 2"];
f[2]

Part VI. Functions

Main Menu  Part: I  II  III  IV  V  VI  VII

2. Differentiating between Functions and Ordinary Expressions

An ordinary expression has a variable name on the left hand side, an equals sign, and an expression on the right hand side.  For example

Clear[t,y,z]
Print["This assigns the value 3 to the variable y"];
y=3
Print["This assigns the espression t+2 3 to the variable y"];
y=t+2
Print["This assigns the expression y^(2t) to the variable z"];
z=y^(2t)

Variables (or parameters) on the right hand side of ordinary expressions are not dummy variables.  They become part of the definition of the variable on the left hand side immediately upon making the assignment.  Consider the result if we assign the value of 2 to y and then display z ( which was defined to depend on y).

Print["This is a new expression for y"];
y=2
Print["This is the new expression for z"];
z

z was defined to be y^(2t) when y was equal to t+2.  Changing the value of y does not change the value of z.  Consider what happens if we define the left hand side variable to be the expression f[x] without the underscore on the x.

Clear[f,x,t];
f[x]=x^(2t);
f[x]
Print["This is function f[x] defined to be  f[x] = ", f[x]];

Print["These are the results if we ask for this 'function' evaluated at x = 4 or x = 7"];
f[4]
f[7]

f[x] is a variable name for the expression y^(2t) and f[4] is another variable name to which no expression is assigned.  We could assign a value to the variable x using the replacement operator in the following fashion.

f[x]/.x->4
f[x]/.x->6

Another way to think about this is as follows.
		f[x_] := value,   definition for any expression with dummy argument x, evaluated when called.
		f[x]   =  value,  definition for a specific expression x, the left hand side variable is not a function.

Part VI. Functions

Main Menu  Part: I  II  III  IV  V  VI  VII

3. Delayed versus Immediate Assignment

An alternative way to define functions is to use immediate assignment.  When assignment is immediate, the function will be evaluated at the time it is defined.  Consider first an example where f is a function of x and x occurs explicitly on the right hand side.

Clear[f,x];
f[x_]=x^2+5

The function f is immediately assigned the value x^2 +5.  The result of this assignment is immediately displayed.  Evaluating this expression, replacing the dummy variable x with various other expressions will give results as follows.

Clear [x,y,t]
f[x]
f[3]
f[y]
f[t+2]
f[y+t]//Expand

This is similar to what we obtained when we used delayed assignment because x is on the right hand side of the expression. 
Now consider what happens if we define an equation with an expession involving x on the right hand side and then define f[x] as a function of this equation using immediate assignment.

Clear[f,x];
eq1=x^2+5;
Print["This is the equation eq1, ", eq1];
f[x_]=eq1;
Print["This is function defined to be f[x_] = eq1"];
f[x]
Print["This is the function evaluated at x = 4"];
f[4]
Print["This is the function evaluated at x = 6"];
f[6]

In the above case we used immediate assignment to define eq1 and to define the function f, also using immediate assignment.
Now consider what happens if we define eq1 using immediate assignment and then define the function f using delayed  assignment.

Clear[f,x, eq1];
(* Assign the expression x^2+5 to eq1 *)
eq1=x^2+5;
Print["This is the equation eq1 = ", eq1];
f[x_]:=eq1;
Print["This is f[x_] defined as a funciton of eq1 "];
f[x]
Print["This is the function f[x] evaluated at x = 4"];
f[4]
Print["This is the function evaluated at x = 6"];
f[6]

This is not the result you might have expected.  With delayed assignment, when the function f is called, the expression eq1 is already assigned to f and there is no substitution for x in eq1. With delayed assignment, eq1 will be substituted for f[ ] and the answer will always be 5 + (x^2).  To obtain the desired result we call f[x] with any argument and then use the ReplaceAll ( /. ) command to assign the value x = 4.

Clear[f,x, eq1];
(* Assign the expression x^2+5 to eq1 *)
eq1=x^2+5;
Print["This is the equation eq1 = ", eq1];
f[x_]:=eq1;
Print["This is f[x_] defined as a funciton of eq1 "];
f[x]
Print["This is the function f[x] evaluated at x = 4"];
f[4]/.x->4
Print["This is the function f[x] evaluated at x = 6"];
f[4]/.x->6
Print["This is also the function evaluated at x = 6"];
f[b]/.x->6

The argument of f makes no difference in the last case because the value of x is being assigned using the ReplaceAll ( /. ) command to assign the value x = 4.
There is yet another way to define the function f to obtain the desired result.  Instead of defining eq1 as an expression to which a value is immediately assigned, we define a function eq1[x_] using delayed assignment and then define f[x_] as a function of eq1[x], also using delayed assignment. When we call the function f[x], eq1[x] will be evaluated at that time.  Consider the example below.

Clear[f,x, eq1];
(* Assign the expression x^2+5 to eq1 using delayed assignment *)
eq1[x_]:=x^2+5;
Print["This is the equation eq1[x] = ", eq1[x]];
f[x_]:=eq1[x];
Print["This is f[x_] defined as a funciton of eq1 "];
f[x]
Print["This is the function f[x] evaluated at x = 4"];
f[4]
Print["This is the function f[x] evaluated at x = 6"];
f[6]

The output here is the same as when we used delayed assignment and subsequently used the ReplaceAll ( /. ) command to substitute for x.

Part VI. Functions

Main Menu  Part: I  II  III  IV  V  VI  VII

4. Functions Involving Variables and Parameters

First consider the simplest case from the first section on functions where f is defined using delayed assignment and the values of the parameters are specified before we call the function.

Clear[f,a,b,c,x];
a=1; b=-4; c=2;
Print["These are the initial parameters a = ",a,"  b = ", b, " and c = ",c];
Print["This is the function f using delayed assignment"];
f[x_]:=a*x^2+b*x+c
f[x]
Print["This is the function f[x] evaluated at x = 4"];
f[4]
Print["This is the function f[x] evaluated at x = 6"];
f[6]

Now consider the the effect of changing these parameters.

Clear[f,a,b,c,x];
a=1; b=-4; c=2;
Print["These are the initial parameters a = ",a,"  b = ", b, " and c = ",c];
Print["This is the function f using delayed assignment"];
f[x_]:=a*x^2+b*x+c
f[x]
Print["This is the function f[x] evaluated at x = 4"];
f[4]
Print["This is the function f[x] evaluated at x = 6"];
f[6]

(* Now set new values for the parameters *)
a=3; b=3;  c=-2;
Print["These are new parameters a = ",a,"  b = ", b, " and c = ",c];
Print["This is the function f[x]"];
f[x]
Print["This is the function f[x] evaluated at x = 4"];
f[4]
Print["This is the function f[x] evaluated at x = 6"];
f[6]

Now consider the the effect of immediate assignment of expressions involving parameters where again we define the values of the parameters before we call the function.

Clear[g,a,b,c,x];
a=1; b=-4; c=2;
Print["These are the initial parameters a = ",a,"  b = ", b, " and c = ",c];
Print["This is the function g using immediate assignment"];
g[x_]=a*x^2+b*x+c
Print["This is the function g[x] evaluated at x = 4"];
g[4]
Print["This is the function g[x] evaluated at x = 6"];
g[6]
(* Now set new values for the parameters *)
a=3;  b=3;  c=-2;
Print["These are new parameters a = ",a,"  b = ", b, " and c = ",c];
Print["This is the function g[x]"];
g[x]
Print["This is the function g[x] evaluated at x = 4"];
g[4]
Print["This is the function g[x] evaluated at x = 6"];
g[6]

Notice that the values for g are the same as before the parameter change. Because g is defined immediately, changes in the parameters, a, b, and c, have no impact on it when subsequently evaluated.  The function g[x_] will have the initial values of a, b, and c in all expressions after its initial definition.

Now consider the use of parameters with functions that are defined based on other expressions or functions.  First consider the case where the expression and the function are defined using immediate assignment.

Clear[g,x,a,b];
a=2; b = -2;
Print["These are the initial parameters a = ",a,"  b = ", b];
eq1=a*x^2+b;
Print["This is the equation eq1, ", eq1];
g[x_]=eq1;
(* This assignment statement makes g[x] immediately equal to 2x^2-2.  The x is a fixed parameter in eq1, but a dummy variable in g[x]. This is the same as writing g[x_] = 2x^2 - 2 *)
Print["This is function defined to be g[x] = eq1 based on immediate assignment, g[x] = ", g[x]];
Print["This is the function g evaluated at x = 4"];
g[4]
Print["This is the function g evaluated at x = 6"];
g[6]
(* Now set new values for the parameters *)
a=3; b=3;
Print["These are new parameters a = ",a,"  b = ", b];
Print["This is the function g[x]"];
g[x]
Print["This is the function g evaluated at x = 4"];
g[4]
Print["This is the function g evaluated at x = 6"];
g[6]

The change in the parameters has no impact because g was immediately assigned the expression on the right hand side, i.e., 2x^2-2.  The parameters a and b are no longer part of this expression and so changing their value has no impact.

Now consider what happens with immediate assignment of the expression but delayed assignment of the function.  In this case eq1 will be assigned the expression 2x^2-2.  We can then define a function f[x_] := eq1 using delayed assignment.  This will be evaluated in two steps.  In the first step Mathematica will assign a value or variable to x.  For example if we called the function with the command f[4], Mathematica will try to replace x in f[ ] with 4.  This will result in f[4]= eq1.  In the second step, Mathematica will replace eq1 with the assigned expression 2x^2-2.  The final result will be f[4] = 2x^2-2.

Clear[f,x,a,b];
a=2; b = -2;
Print["These are the initial parameters a = ",a,"  b = ", b];
eq1=a*x^2+b;
(* This assignment statement makes eq1 equal to 2x^2-2.  The x is a fixed parameter in eq1, but a dummy variable in f[x] *)
Print["This is the equation eq1, ", eq1];
f[x_]:=eq1;
Print["If we evaluate the function at x, the results is as follows" ];
f[x]
Print["If we evaluate the function at z, the results is as follows" ];
f[z]
Print["If we evaluate the function at 4, the results is as follows" ];
f[4]
Print["If we evaluate the function at 6, the results is as follows" ];
f[6]

(* Now set new values for the parameters *)
a=3; b=3;
Print["These are new parameters a = ",a,"  b = ", b];
Print["This is the function f[x]"];
f[x]
Print["This is the function f evaluated at x = 4"];
f[4]
Print["This is the function f evaluated at x = 6"];
f[6]

We again do not obtain the desired result because eq1 was assigned a value immediately and that value will not change even if we change the parameters.  An alternative would be to make the assignment to eq1 on a delayed basis so that it is only receives a value when the expression is evaluated.  So consider what happens if eq1 is an expression with delayed assignment and f is a function using delayed assignment.

Clear[f,x,a,b];
a=2; b = -2;
Print["These are the initial parameters a = ",a,"  b = ", b];
eq1:=a*x^2+b;
Print["This is the equation eq1 using delayed assignment, ", eq1];
f[x_]:=eq1;
Print["This is function defined to be f[x] = eq1 based on delayed assignment, f[x] = ", f[x]];
Print["This is the function f evaluated at x = 4"];
f[4]
Print["This is the function f evaluated at x = 6"];
f[6]
(* Now set new values for the parameters *)
a=3; b=3;
Print["These are new parameters a = ",a,"  b = ", b];
Print["This is the function f[x]"];
f[x]
Print["This is the function f evaluated at x = 4"];
f[4]
Print["This is the function f evaluated at x = 6"];
f[6]

Notice that when we evaluate f[4], the answer is -2+2x^2.  This occurs because Mathematica evaluates this command in two steps.  In the first step Mathematica assigns a value or variable to x.  For example if we called the function with the command f[6], Mathematica will try to replace x in f[ ] with 6.  This will result in f[6]= eq1.  In the second step, Mathematica will replace eq1 with the delayed assigned expression. As a result, f[z] will always result in ax^2 +b, independent of the value of z.  
The first time we call f[x], the intial set of parameters will be used.   The second time we call f[x], the new set of parameters will be used.   The expression for f now changes as the parameters change,but the value is equal to ax^2 +b independent of the value with which we call f.  The parameters a and b will change, but f[z] will always yield ax^2 +b.

To actutally evaluate f[ ] with a different argument, we can use the ReplaceAll ( /. )  command.

Clear[f,x,a,b];
a=2; b = -2;
Print["These are the initial parameters a = ",a,"  b = ", b];
eq1:=a*x^2+b;
f[x_]:=eq1;
Print["This is function defined to be f[x] = eq1 based on delayed assignment"];
f[x]
Print["This is the function f evaluated at x = 4"];
f[x]/. x-> 4
(* Now set new values for the parameters *)
a=3; b=3;
Print["These are new parameters a = ",a,"  b = ", b];
Print["This is the new function f[x]"];
f[x]
Print["This is the function f evaluated at x = 4"];
f[x]/. x-> 4

The expression eq1 is defined based on the initial parameters and is not a function that is defined expicitly with x as the argument.  To define eq1 as an explicit  function of x, where x can be viewed as a dummy variable, to be replaced later with a value, we would need to use the standard function definition, i.e., eq1[x_]:= ax^2+b.    Consider what happens when we define eq1 as a function of x with parameters and delayed assignment and then define f[x_] as a function of eq1[x], also using delayed assignment.  When we call the function f[x], eq1[x] will be evaluated at that time.  Consider the example below.

Clear[f,x, a,b,eq1];
a=2; b = -2;
Print["These are the initial parameters a = ",a,"  b = ", b];
(* Assign the expression ax^2+b to eq1 using delayed assignment *)
eq1[x_]:=a*x^2+b;
Print["This is the equation eq1[x] = ", eq1[x]];
f[x_]:=eq1[x];
Print["This is f[x_] defined as a funciton of eq1 "];
f[x]
Print["This is the function f[x] evaluated at x = 4"];
f[4]
(* Now set new values for the parameters *)
a=3; b=3;
Print["These are new parameters a = ",a,"  b = ", b];
Print["This is the new equation eq1[x] = ", eq1[x]];
Print["This is the new function f[x]"];
f[x]
Print["This is the function f evaluated at x = 4"];
f[4]

Finally consider what happens if we define eq1 and f as functions of two parameters (a, b) and one variable (x).

Clear[f,x, a,b,eq1];
(* Assign the expression ax^2+b to eq1 using delayed assignment *)
eq1[x_,a_,b_]:=a*x^2+b;
Print["This is the equation eq1[x,a,b] = ", eq1[x,a,b]];
f[x_,a_,b_]:=eq1[x,a,b];
Print["This is f[x,a,b] defined as a funciton of eq1 "];
f[x,a,b]
Print["This is the function f[x,a,b] evaluated at x = 4, a = 2, and b = -2"];
f[4,2,-2]
Print["This is the function f[x,a,b] evaluated at x = 4, a = 3, and b = 3"];
f[4,3,3]

Part VI. Functions

Main Menu  Part: I  II  III  IV  V  VI  VII

5. More Function Examples

We can defne functions and use them in a variety ways.

Clear[f,x, y,z,eq1,eq2,g];
(* Assign the expression x^2+5 to eq1 using delayed assignment *)
eq1[x_,y_]:=x^2+y^2+5;
Print["This is the equation eq1[x,y] = ", eq1[x,y]];
eq2[z_]:=z^2+1;
Print["This is the equation eq2[y] = ", eq2[y]];
g[y_]:=y+5;
Print["This is the equation g[y] = ", g[y]];
f[x_]:=eq1[x,y]+ eq2[z];
Print["This is f[x_] defined as a funciton of eq1 "];
f[x]
Print["This is the function f[x] evaluated at x = 4"];
f[4]
y=2;
Print["This is the function f[x] evaluated at x = 4 with y = 2"];
f[4]
Clear[y];
h[x_]:=eq1[x,y]+ g[y];
Print["This is h[x_] defined as a funciton of g "];
h[x]
Print["This is the function h[x] evaluated at x = 4"];
h[4]
y=2;
Print["This is the function h[x] evaluated at x = 4 with y = 2"];
h[4]

Part VI. Functions

Main Menu  Part: I  II  III  IV  V  VI  VII

6. Transformations Involving Functions

We briefly discussed transformation rules of the form x -> value to replace symbols by values in section 12 of part A.  Transformation rules in Mathematica are, however, quite general. You can set up transformation rules not only for symbols, but for any Mathematica expression.
Applying the transformation rule x -> 3 replaces x by 3.

Clear [x, y, f];
1 + f[x] + f[y] /. x -> 3

Consider the following input cell and the resulting output.

Clear[f,a,b,c,x];
a=3;  b=-5;  c=-2;
Print["These are the initial parameters a = ",a,"  b = ", b, " and c = ",c];
Print["This is the command defining the function f[x]"];
f[x_]=a*x^2+b*x+c;  f[x]
Print["This defines a new quantity z"];
z=1+f[x]+f[y];  z
Print["This defines a new quantity z3 replacing x with 3"];
z3=z/.x->3;  z3
Print["This defines a new quantity z32 replacing x with 3 and y with 2"];
z32=z /.{x->3, y->2};  z32

Now consider a case where f is defined without the blank _ so that f[t] is just f[t], not a function evaluated at t.  Then we can replace f[t] later with a delayed assignment

Clear[f,a,b,c,x];
a=3;  b=-5;  c=-2;
Print["These are the initial parameters a = ",a,"  b = ", b, " and c = ",c];
Print["This is the command defining the function f[x]"];
f[x]=a*x^2+b*x+c;  f[x]
Print["This defines a new quantity z"];
z=1+f[x]+f[y];  z
Print["This defines a new quantity z3 replacing x with 3"];
z3=z/.x->3;  z3
Print["This defines a new quantity z4 replacing x with 3 and y with 2"];
z4=z /.{x->3, y->2};  z4
Print["This defines a new quantity z5 replacing y with its square"];
z5=z /.f[t_]->t^2;  z5

Notice that f[x], which was immediately assigned an expression, remains the same, while the generic function f[y] is replaced with the expression y^2.  Now consider some more complicated examples.

Clear[x];
Print["With x not assigned a value, the variable z is defined as z = ", z]
Print["This is an equation eq2"];
eq2 = x^2+1; 
eq2
Print["This defines a new quantity z6 replacing y with the equation defined by eq2"];
z6=z /.f[t_]->eq2;  z6
Print["If we evaluate z6 at x = 2 we obtain"];
z6/.x->2
Print["This is a new equation eq3"];
eq3:=x^2+3 
eq3
Print["This defines a new quantity z7 replacing y with the equation defined by eq3"];
z7=z /.f[t_]->eq3;  z7
Print["If we evaluate z7 at x = 2 we obtain"];
z7/.x->2
Print["With x not assigned a value, the variable z is defined as z = ", z]
(* Now set x = 3 *)
x=3;
Print["With x = 3, z is now given by z = ", z]
Print["If we evaluate z8 with eq3 having delayed assignment with x = 3 we obtain"];
Print["z = ", z]
z8=z /.f[t_]->eq3;  z8

You can set up transformation rules for expressions of any form.  See if you can interpret the input and output in the following cell.

Clear[f,x,y,a,b,c,d,p]
z=f[a b]+f[c d]/.f[x_  y_]->f[x]+f[y]
z/.{a->2,c->3}
1+x^2+x^3/.x^p_->f[2*p]

Part VII      Solving Equations

Main Menu  Part: I  II  III  IV  V  VI  VII

Contents

1. Solving Polynomial Equations in One Variable (Exact solutions)
		2. Solving Defined Equations and Substituting in Solutions
		3. Solving Polynomial Equations in Two or More Variables
		     4.  Solving Equations Numerically
		     5. Solving Equations Which are Not Polynomials (FindRoot)

Part VII. Solving Equations

Main Menu  Part: I  II  III  IV  V  VI  VII

1. Solving Polynomial Equations in One Variable (Exact Solutions)

Solve[lhs == rhs, var] attempts to solve exactly an equation for the variable var.  Usually the equation  has to be a polynomial equation in order for Solve to find the exact solution, but some other equations can also be solved.  Consider the following example equation .

Clear[x]
Solve [ x^2 - 2x - 8 == 0, x]

or

Clear[x];
sol = Solve [ x^2 - 2x - 8 == 0, x]

where we give the name 'sol' to the set of solution rules. The solution is in the form of a list of transformation rules.
If we give a name to the solution rules( 'sol' in this case), we can obtain just a list of solutions by applying the replacement operator /. as follows.

x /. sol

If you want just one of the solutions, extract the appropriate element of the list, e.g. to get the first root in the above example,

x /. sol[[1]]

Being able to extract and use elements of the output of Mathematica procedures is one of the most powerful elements of Mathematica.  For example, the solutions to an equation can then be used in subsequent equations.  The following example creates variables for later use by utilizing the /. and assignment commands.

Clear[f,x,sol,xstar,xstar1,xstar2,xstarsq];
Print["This is the solution to the polynomial equation x^2 - 2*x - 8 = 0"];
sol=Solve[x^2-2*x-8==0,x]
Print["This creates a vector variable 'xstar' which has the two roots of the equation as elements. "];
xstar=x/.sol;
xstar
Print["The /. commnand replaces x in the expression using the rule x-> -2 or x-> 4. "];
Print["This creates a vector variable 'xstarsq' which has the squares of the two roots of the equation as elements. "];
xstarsq=x^2/.sol;
xstarsq
Print["The /. commnand replaces x in the expression x^2 using the rule x-> -2 or x-> 4. "];
Print["This creates the variables 'x1star' and 'x2star' which are the values of x. "];
xstar1=x/.sol[[1]]
xstar2=x/.sol[[2]]

It is very important in using replacement rules or in selecting part of an expression to carefully choose the correct part of the expression or rule.  Consider the solution to the equation. The rule has two parts {x 6 -2} and {x 6 4}.  If the solution is given the name 'sol', then we refer to these two parts as sol[[1]] and sol[[2]], i.e., 
		sol[[1]] = {x 6 -2}
		sol[[2]] = {x 6 4}
These two parts each have one element, i.e., 
		sol[[1,1]] = x 6 -2
		sol[[2,1]] = x 6 4
And each of these elements has two parts, i.e., 
		sol[[1,1,1]] = x
		sol[[1,1,2]] = -2
		sol[[2,1,1]] = x
		sol[[2,1,2]] = 4
To see how this all works consider the following input cell.

Print["We can also create solution vectors and variables directly by setting a variable equal to elements of the solution rules. "];
Print["This creates a vector variable 'χstar' which has the two roots of the equation as elements. "];
χstar=sol;
χstar
Print["This creates a variable 'χstarr1 = sol[[1,1]]' which is the first rule. "];
χstarr1=sol[[1,1]]
Print["This creates a variable 'χstarr2 = sol[[2,1]]' which is the second rule. "];
χstarr2=sol[[2,1]]
Print["This creates a variable 'χstara = sol[[1,1,1]]' which is the first element of the first rule. "];
χstara=sol[[1,1,1]]
Print["This creates a variable 'χstar1 = sol[[1,1,2]]' which is the second element of the first rule. "];
χstar1=sol[[1,1,2]]
Print["This creates a variable 'χstarb = sol[[2,1,1]]' which is the first element of the second rule. "];
χstarb=sol[[2,1,1]]
Print["This creates a variable 'χstar2 = sol[[2,1,2]]' which is the second element of the second rule. "];
χstar2=sol[[2,1,2]]
Print["This shows that the elements of sol are two rules, so sol[[1,2,1]] and sol[[2,2,2]] do not exist.  The rules have two parts: sol[[2,1,1]] and sol[[2,1,2]] .  "];
χstarc=sol[[1,2,1]]
χstarc=sol[[2,2,2]]

Notice than sol[1, 2 , ▪ ] and sol[2 , 2 ,▪ ] are not defined because {x->2} and {x-> 4} are single elements of sol, whereas as x-> -2 and x-> 4 have two parts.
As another example, consider the following cubic equation.

Clear[f,g,x,y,z,sol];
Print["This is the solution to the polynomial equation x^3-5x^2-2x+24"];
sol = Solve[x^3-5 x^2-2 x+24== 0, x]
Print["This create a vector variable 'xstar' which has the three roots of the equation as elements"];

xstar = x/.sol; xstar
Print["This creates the variables 'x1star', 'x2star' and 'x3star' which are the values of x."]
x1star = x/.sol[[1]]
x2star = x/.sol[[2]]
x3star = x/.sol[[3]]

Part VII. Solving Equations

Main Menu  Part: I  II  III  IV  V  VI  VII

2. Solving Defined Equations and Substituting in Solutions

Rather than specifying the equation within the Solve command, we can name the equation, and then solve it.

Clear[f,g,x,y,z,sol];
Print["This defines an equation"];
eqn=2*x^2-5*x-3
sol=Solve[eqn==0,x]
Print["This creates a vector variable 'xstar' which has the two roots of the equation as elements. "];
xstar=x/.sol;
xstar
Print["This creates the variables 'x1star', and 'x2star' which are the values of x. "];
xstar1=x/.sol[[1]]
xstar2=x/.sol[[2]]

We can also define a function f[x_], and then solve the function both analytically using parameters and also for specific values of the parameters.  If we use delayed assignment for the function f[x_],  we can change the parameters a, b, and c each time we evaluate the answer.  Consider as an example the generic equation

Clear[f,g,x,y,z,sol,a,b,c];
Print["This defines the equation "];
f[x_]:=a*x^2 + b*x + c ;  f[x]
Print["This is the solution to the equation f[x] = 0 "];
sol=Solve[f[x]==0,x]
Print["This creates a vector variable 'xstar' which has the two roots of the equation as elements. "];
xstar=x/.sol
Print["This creates the variables 'x1star' and 'x2star' which are the values of x. "];
x1star=x/.sol[[1]];   x2star=x/.sol[[2]]; 
Print["The first root is ",x1star]
Print["The second root is ",x2star]
Print["This replaces a, b, and c in the solution with numeric values a= 2, b = -3 and c = -2 "]
xhat1=sol[[1,1]] /.{a->2,b->-3,c->-2}
xhat2=sol[[2,1]] /.{a->2,b->-3,c->-2}

We can also define the parameters, a, b, and c, before solving the equation.  In this case, the solution will not involve parameters, but parameter values.  If we try to substitute new values for a, b, and c in the solution, we get the original answers because a, b, and c are not part of the solution.

Clear[f,g,x,y,z,sol,a,b,c];
Print["This defines the parameters "];
Print["This defines the equation "];
f[x_]:=a*x^2 + b*x + c ;  f[x]
Print["This is the solution to the equation f[x] = 0 "];
sol=Solve[f[x]==0,x]
Print["This creates a vector variable 'xstar' which has the two roots of the equation as elements. "];
xstar=x/.sol
Print["This creates the variables 'x1star' and 'x2star' which are the values of x. "];
x1star=x/.sol[[1]];   x2star=x/.sol[[2]]; 
Print["The first root is ",x1star]
Print["The second root is ",x2star]

We can replace a,b and c with numeric values as follows.

Print["This replaces a, b, and c in the solution with numeric values a= 2, b = -2 and c = -4 "]
Print["This is the expression assigned to sol[[1,1]] ",sol[[1,1]] ]
Print["This is the expression assigned to sol[[2,1]] ",sol[[2,1]] ]
Print["These are the roots of the equation after assigning nmumbers to a, b, and c "]
xhat1=sol[[1,1]] /.{a->2,b->-2,c->-4}
xhat2=sol[[2,1]] /.{a->2,b->-2,c->-4}

Part VII. Solving Equations

Main Menu  Part: I  II  III  IV  V  VI  VII

3. Solving Polynomial Equations in Two or More Variables

We can also solve systems of equations using the Solve command.  Consider the following example.

Clear[f,g,x,y,z,sol];
Solve[{3x+6y==0,4x+2y==12},{x,y}]

The equations to be solved are enclosed in curly brackets {} followed by a comma.  The variables for which we want to solve are also enclosed in curly brackets, separated by a comma.  Consider the following example.

Clear[f,g,x,y,z,sol];
Solve[{3x+6y==0,4x+2y==12},{x}]

The empty curly braces indicate that there is either no solution to the equation or an infinite number of solutions.  We can also define the equations separately and then solve as follows.

Clear[f,g,x,y,z,sol,eq1,eq2];
eq1=3x+6y==0;
eq2=4x+2y==12;
Solve[{eq1,eq2},{x,y}]

Solve also works for non-linear equations.

Clear[f,g,x,y,z,sol,eq1,eq2];
eq1=4*x^2 - 3*x - 2*y;
eq2=2*y^2 - 6*y - 10 *x;
Solve[{eq1==0,eq2==0},{x,y}]

Part VII. Solving Equations

Main Menu  Part: I  II  III  IV  V  VI  VII

4. Solving Equations Numerically

For equations that do not have analytical solutions, we can find a solution using numeric methods.  This works well for polynomials of higher orders as well as for some other equations.  Consider solving the equation

Clear[f,g,x,y,z,sol,eq1,eq2];
eq1=x^3+7/2*x^2+2*x-2;
Solve[{eq1==0},x]

We can also solve the equation numerically using the NSolve command.

Clear[f,g,x,y,z,sol,eq1,eq2];
eq1=x^3+7/2*x^2+2*x-2;
NSolve[{eq1==0},x]

The answer is the same, except that NSolve produces decimal approximations instead of exact values.
Consider what happens when we use Solve and  NSolve on equations containing decimal numbers.

Clear[f,g,x,y,z,sol,eq1,eq2];
eq1=x^3+3.5*x^2+2*x-2;
Solve[{eq1==0},x]
NSolve[{eq1==0},x]

The solutions are the same.  For polynomials of degree four or less (and some of higher degree)  Solve and  NSolve will find the same solution.  For higher degree polynomials, Solve may not be able to find an exact solution.  Consider the following example.

Clear[f,g,x,y,z,sol,eq1,eq2];
eq1=-24+2 x+29 (x^2)-3 (x^3)-5 (x^4)+(x^5);
Solve[{eq1==0},x]
NSolve[{eq1==0},x]

In this case, Solve is able to find a solution.  Now consider a different equation

Clear[f,g,x,y,z,sol,eq1,eq2];
eq1=-22.5+14 x+27 (x^2)-3.5 (x^3)-5.6 (x^4)+3(x^5) +x^6+7*x^7;
Solve[{eq1==0},x]
NSolve[{eq1==0},x]

Again the solutions are the same.  The lesson is that for many polynomials, Solve is able to find exact solutions.

Part VII. Solving Equations

Main Menu  Part: I  II  III  IV  V  VI  VII

5. Solving Equations Which are Not Polynomials (FindRoot)

Solve and NSolve only work when the equations involved are polynomials or close to being polynomials.  When this is not the case, we need to use an alternative function called FindRoot.  This will numerically search for the solution to an equation. Consider the following example ( Solve and NSolve cannot solve it).

Clear[f,g,x,y,z,sol,eq1,eq2];
eq1=x^2+Log[3*x]-4x;
Solve[{eq1==0},x]
NSolve[{eq1==0},x]

To find numerical solutions of non-polynomial equations that are usually not solvable using Solve or NSolve, We use the FindRoot procedure.  The syntax is as follows.
	FindRoot[lhs == rhs , {x, x0}]
where x0 is an initial guess for x to be used by the algorithm.  Whereas NSolve finds all the solutions of a polynomial, FindRoot will at most give one root.  If the equation has more than one root, the one obtained depends on the choice of the initial guess  The procedure usually find the root closest to that intial guess. Here is the result of applying FindRoot to the previous equation.

Clear[f,g,x,y,z,sol,eq1,eq2];
eq1=x^2+Log[3*x]-4x;
FindRoot[{eq1==0},{x,2}]

If we do not choose an appropriate starting value, the FindRoot algorithm may not converge.  This is demonstrated in the following set of cells where we plot the function to see its behavior and choose a starting value in an area where the function maybe misleading.

Clear[f,g,x,y,z,sol,eq1,eq2];
eq1=(x^2)+Log[3 x]-4 x;
Plot[eq1,{x,0,7},AxesStyle->{RGBColor[0.8`,0.2`,0.1`],Thickness[0.011`]},PlotStyle->{RGBColor[0.1`,0.3`,0.8`],Thickness[0.011`]},BaseStyle->{FontColor->RGBColor[0.1`,0.1`,0.1`],FontWeight->"Bold",FontFamily->"Times",FontSize->14},PlotLabel->Style["Graph of x^2 +Log[3*x] - 4x",FontSize->18,FontColor->RGBColor[0.1`,0.2`,0.3`]]]
FindRoot[{eq1==0},{x,0.00001`}]