Physics 230 -- Lab 2 (Functions and Lists)

Fall 2015 - Transtrum

Labs developed by John S. Colton, BYU Physics & Astronomy, based in part on past labs by Branton Cambell and Steve Turley.

Remember the three most helpful pieces of advice you will get this semester, from Lab 1:  

Probably the most helpful advice you will get this semester: If you are typing Mathematica commands and things are not working the way you expect, go to Evaluation→Quit Kernel→Local. That clears the memory and will restart the Mathematica engine the next time you enter a command. Just as the way to solve most computer problems is to turn it off and on again, the way to solve most Mathematica problems is to turn off the kernel (the processing engine) and then turn it on again. Evaluation→Abort can also be quite useful, to stop the execution of the current command if things are taking much longer than expected. 

The second most helpful piece of advice you’ll get this semester: Mathematica has outstanding online help. To find out more information about any function, click on the function name and press F1. You can also access help topics organized by category, and/or search for a particular topic by going to Help→Documentation Center. One cool feature is that you can actually edit examples inside the help documents and execute them with shift-enter.

The third most helpful advice you will get this semester: Be very VERY careful when choosing between parentheses (always used for arithmetic grouping), square brackets (always used in function calls/definitions), and braces (always used for lists of items). Mathematica is EXTREMELY picky about which is which, and will give you errors if you use them incorrectly.

---

More on clearing the memory to solve problems--as mentioned above, quitting the kernel is an excellent way to solve issues if your computer starts giving you results that don’t make sense. But often you can solve problems by clearing the memory without doing a full kernel reboot. There’s a command for that:

Clear["`*" ]

That command will erase the definitions of any symbols used previously so that they don't interfere with subsequent work that employs the same symbol names for different purposes. It’s often a good idea to start each new notebook with that command so that variables defined in other notebooks that have been executed won’t inadvertently affect the current notebook. Here, the  *  is a wildcard symbol that refers to all variables that have been defined, and the  `  character signifies the current session (i.e., the command means “clear all variables that have been defined in the current session”).

Advanced Function Definition

Quick review

In Lab 1 you learned the basic steps of how to define your own functions, such as this to define f(x)=(x^2)+3x:

f[x_] = x^2 + 3x

f[2]

How to use slash-dot notation

As mentioned in the last lab, the arrow symbol (obtained via "-" followed by ">" ) is often used to specify parameters in function arguments. It can also be used to instruct Mathematica to replace one quantity with a different quantity, when paired with a “slash-dot”:

x^2 + 3x

x^2 + 3x  /. x->2

notafunction = x^2 + 3 x

notafunction /. x->2

notafunction /. x-> y^2

Plot[notafunction,{x,-4,4}]

Things to notice: 

1. The “slash-dot” can be read in English as the word “with”. The arrow symbol can be read as “replaced by”. Thus the command “x^2 + 3x  /. x->2” can be read as “x^2 + 3x, with x replaced by 2”. So it gives you a result of 2^2 + 3*2 (= 10).

2. Slash-dot can be used to mimic the behavior of functions. The expression “notafunction” is not a function, rather it is a variable that contains an algebraic expression involving x. But “notafunction” can be used to mimic the behavior of a function because an expression with the variable replaced by a number is essentially the same as a function evaluated at the number.

3. As in the   /. x-> y^2   example, slash-dot can be used to replace a variable with basically anything, including a function of another variable.

4. The Plot function example doesn’t involve slash-dot directly, but it’s doing much the same thing--“notafunction” is being interpreted as a particular expression involving x’s, so the command is essentially the same as typing in “Plot[x^2 + 3 x,{x,-4,4}].  Plotting things that way can be useful, but do so carefully. Things don’t always work as expected--the value of the “notafunction” variable could get accidentally changed, for example. In my opinion the following method is generally safer/better:

thisisafunction[x_] = x^2+3x   (* Now this IS a function, not just a variable defined to be equal to an expression involving x *)

Plot[thisisafunction[x],{x,-4,4}]

Slash-dot usage with FindRoot and Solve. Slash-dot can be used to make the solutions to FindRoot and Solve appear/behave a little more normally. Look at the difference between the outputs of these commands:

FindRoot[Cos[x]==x, {x,1}]  (* from last lab *)

x /. FindRoot[Cos[x]==x, {x,1}]

Solve[3 x^2 == 4 (3 x - x^2) +5, x]  (* from last lab *)

x /. %

N[%]

Things to notice: 

1. FindRoot and Solve actually return rules as their output. (I do not know why this is the case.) The fact that an output expression is a rule rather than a number is indicated by the arrow. The output of the first FindRoot command is the rule “x is to be replaced by 0.739085”.

2. The rules returned by those commands can be used as the second part of a slash-dot command. Thus, the second input can be read like this: “x, with x replaced by 0.739085”. This of course gives you just 0.739085.

Assignment 1. Three slash-dot tasks

(a) Use slash-dot notation to figure out what this complicated expression is equal to when x is 4:  1/(3 (1+x))-(-1 + 2x)/(6 (1-x +x^2))+2/(3(1 + (1/3) (-1 +2 x)^2)).  
(b) Figure out the expression in terms of y, given x = 2y (and simplify your result)
(c) Define the following two expressions: (Subscript[y, 1])=x sin(x) and (Subscript[y, 2])=(e^x). When plotted, the two curves intersect in an infinite number of places. Use FindRoot to find the intersection that occurs closest to x=0, and use slash-dot to determine what the y-value of the intersection is without doing any copying & pasting of your own.

Delayed function assignments with :=

Sometimes functions are defined with  :=  instead of with  =.  This causes a subtle difference in the way Mathematica handles the function. With equals, the function is immediately defined as was specified by the right hand side of the equation. With a colon-equals, the function definition is postponed until it is actually called later. And it’s reevaluated each time it’s called. Evaluate the following two cells and think through the results carefully.

m=2;
a[x_] = m x^2  (* immediate assignment -- evaluated right now *)
b[x_] := m x^2   (* delayed assignment -- not evaluated until used later *)
a[4]
b[4]

(The two outputs are the result of the a[1] and b[1] commands, in order.)

m = 3;

a[4]  (* uses the original value of m that was in force when the assignment was first made *)
b[4]   (* reevaluated now using the current value of m *)

Things to notice: 

1. The function a(x) was defined to be 2 x^2 for all time (or at least, until it gets redefined).

2. The function b(x) was defined to be m x^2, NOT 2 x^2.  Each time the function b(x) is used, Mathematica has to detect what the value of m is in order to evaluate the function. That’s why the value of b(1) in the second cell is different than the value of b(1) in the first cell.

3. The function definition b[x_] := m x^2  generates no output (because it’s not evaluated yet!). In that respect it’s like there is a semicolon at the end of the line.


Final notes on this topic: 

If it’s not clear why this might be useful, don’t fret. The advantages of  =  over  :=, or vice versa, will become clearer as you gain more experience. For now, if a function definition doesn’t work the way you think it ought to, just remember that perhaps you should have used := instead of =  (or vice versa). 

Also, you can use this  :=  notation for any type of assignment that you’d normally do with a regular equals sign, not just for functions.

How to use Postfix notation

In addition to the standard g[x] form for calling a function, Mathematica provides several different alternate forms for calling functions. One of these is the “postfix” form, indicated by two slashes: //.  The following two function calls are equivalent:

g[x]     (* function call in standard notation *)
x//g  (* equivalent shorthand call in "postfix" notation *)

The postfix notation is a bit like “Reverse Polish Notation” (RPN) if you have ever used an HP calculator or are familiar with the concept of a “stack”.

Log[2.4]

2.4 //Log  (* the same thing! *)

N[Sin[1]]

Sin[1] //N

ArcSin[.7]  /Degree

Things to notice: 

1. The second log command can be thought of in English as: “Consider the number 2.4.  Now take the log of it.”

2. I personally find the postfix method of forcing a numerical answer ( //N ) to be extremely helpful.

3. There’s not an easy way of specifying a second argument via postfix form. So if you want sin(1) to 50 decimal places it’s usually best to use something like N[Sin[1],50].

4. The constant “Degree” is equal to pi/180, the conversion factor for going from degrees to radians. To go from radians to degrees, you can divide by it. Its slash has nothing to do with postfix form; it’s simple division. But it’s included here because it sort of works to think of it as a “convert to degrees” postfix function.

How to use Prefix notation

Another alternate way of calling a function is the “prefix” form, indicated by an at sign: @.  The following two function calls are equivalent:

g[x]     (* function call in standard notation *)
g@x      (* equivalent shorthand call in "prefix" notation *)

The expression "g@x" can be read as "g evaluated at x"

g[x_]=Sqrt[x/3];
g[13]
g@13

Pure functions or “nameless” functions

Sometimes you may want to define a function and use it, without ever giving it a name. This can be done in a single line. The construct is a bit abstract but can be extremely powerful. We’ll see much more of it later in the semester. The format for this involves two special symbols:
# = indicates the variable; you can think of it as “x” if you like 
& = indicates the end of the function definition

The # and & symbols are actually shortcuts for the Slot and Function commands, respectively. And Mathematica calls these pure functions instead of the name I prefer, “nameless functions”.

When used in the context of commands that require f[x], the “[x]” must be added by hand. Here are two examples:

(3^#)& [x] /. x-> 3.5  (* calculates 3^3.5 *)

Plot[(1/#) & [x], {x,-2,2}]  (* plots 1/x *)

Things to observe:
1. The parentheses aren’t strictly speaking necessary, but can be helpful to visually separate the function definition from the rest of the line. The & symbol could be placed either inside or outside the parentheses.
2. As mentioned, the ampersand, &, indicates the end of the function definition. Thus “3^# &” defines the 3^x function and “#^2 &” defines the x^2 function.

Nameless functions combined with prefix notation

My experience is that prefix notation (using @) and nameless functions (using # and &) are most useful when combined together. That way you don’t need the clunky “[x]” after the nameless function definition as in the two examples above. The 3^3.5 calculation becomes much shorter, like this:

(3^#)&  @3.5  (* calculates 3^3.5 *)

Nameless functions can be very useful when you want to do the same calculation for several numbers in a row (in the following case, the numbers 12, 13, and 14).

(Sqrt[#/3] & )  @ {12,13 ,14} //N

Things to observe:
1. The numbers 12, 13, and 14 are grouped together in braces to form a “list”. More on lists below.
2. Did you notice I combined prefix with postfix notation by adding //N at the end?
3. I would interpret that command in standard English to read something like, “Consider the numbers 12, 13, and 14. One at a time, divide the numbers by three, and take the square root. Oh yeah, and don’t forget to express the answers in numerical form.” Make sure you can understand where each part of that sentence comes from.

You can actually call regularly-defined functions with a list of numbers as well. This is the equivalent of that one-line command:

f[x_] = Sqrt[x/3];
f[{12,13,14}] //N

An aside: It turns out you can use nameless functions to give a second argument to a postfix command. Here’s how you could do the N[Sin[1],50] command referred to above, in postfix form (if you really wanted to). The “// N[#,50] &” part gets interpreted as “Take the previously calculated number, and compute it to 50 decimal places.”

1 // Sin //N[#,50]&

Assignment 2. Postfix and prefix calculations

(a) Calculate the numerical value of log(sin(sqrt(exp(7.3)))) using standard commands.
(b) Repeat, using only postfix commands.
(c) Repeat, using prefix form combined with a nameless function.

Assignment 3. Translation to English

Type a sentence or two in standard English that describes what these commands will do (use F1 on the Exp function if you are unfamiliar with it). Then test your guess by executing the commands, and modify your sentences if needed. 
(a) Exp[q] /. q-> 2 //N   
(b) h[x_]  :=  a*Sin[x Degree]   
(c) (Sqrt[#] & )  @ {x,y,z}

Lists

Lists are Mathematica objects that are items grouped together with braces. A list can be any collection of items: numbers, unassigned variables, plots, even other lists.  You' ve already used them in a few limited ways--to specify limits in the Plot command, for example, or to have a function give you values of f(x) for several different x values at once. In addition to their utility in evaluating functions and I would say that the three primary purposes of lists are to (1) serve as “arrays” for programming purposes, (2) allow you to do linear algebra with vectors and matrices, and (3) allow you to manipulate real data. We’ll tackle #1 and #2 today, and #3 in a later lab.

How to create a list.

There are numerous ways to create lists in Mathematica. Look over these examples and press F1 on the function names if it’s not clear what’s going on.

list = {1,2,3,4,5}

list^2

list2={a,b,c,d,e}

list2^2

(#^2 &) @list   (* nameless function to operate on list elements, prefix form *)

Range[10]

Range[10,20]

range = Range[0,10,.2]    (* general format for Range:  start, end, step size *)

(#^2 &) @ range

Table[n^2, {n,3,7}]

Table[n^2, {n,1,5,0.1}]    (* general format for Table: start, end, step size  *)

f[x_] = x^3;
Array[f, 10]

Array[#^3&,10]

Things to observe: There are lots of ways to construct lists! The five ways used there were:
1. Manually defining a list with braces.
2. Operating on an existing list
3. The Range command, to create an equally-spaced set of “points” (list elements)
4. The Table command, as a very flexible way of creating a set of function values
5. The Array command, as a slightly less flexible way of doing the same (with some added capability to create multi-dimensional lists)

I personally favor the Range and Table commands over the Array command.

Assignment 4. Creating lists of even numbers

Use three different ways to create a list of the even numbers from 1 to 100. Each method must use a different function and just a single line of code.

How to plot a list

If you just want to plot a list of numbers, the method is simple:

list=Table[n^2,{n,1,10}]
ListPlot[list, Joined->True]

Things to observe:
1. This is basically a plot of y = x^2.
2. ListPlot works a lot like Plot, to be used if you want to manually specify the x-values for which the function is being plotted. Most of the same options are available. For example, you can plot two lists simultaneously by grouping them together.
3. Figure out what the Joined option does...try plotting it without the Joined option being set to True.

If you are not careful, however, ListPlot may produce unexpected results. What' s wrong with this?

list=Table[n^2,{n,1,10,.5}]
ListPlot[list, Joined->True]

Things to observe:  Notice the x-axis now goes from 1 to 19!  This is no longer a plot of y = x^2.  The reason is that we gave ListPlot a single, simple list, so there’s no way for it to know what x-values are associated with each y-value. Therefore ListPlot defaults to using the list element number as the x-axis. There are 19 elements in our list.

Plotting y vs. x. If you want to specify the x coordinates in order to plot y vs. x, you have to do a little more work. Something like "ListPlot[{xaxis,yaxis}]" isn't quite right--that would actually plot both lists (the x-axis list and the y-axis list), each as a function of list element number.

Instead, you have to give it a list of x-y pairs. Here’s a slick way to generate a list of x-y pairs. It uses the Transpose function which we’ll discuss more later.

xaxis=Range[1,10,.5];
yaxis = Table[n^2,{n,1,10,.5}];    (* could also use "yaxis = xaxis^2;" *)
combinedlist = {xaxis,yaxis} //Transpose

ListPlot[combinedlist,Joined->True]

Things to observe:  Now the plot is y vs. x for the given set of x-values and y-values. Using ListPlot to plot functions point-by-point in this fashion is essential in dealing with real experimental data.

Assignment 5.  ListPlot of a Gaussian function

Create a list of constantly-spaced points from -10 to 10, with a spacing of 0.1. Make a plot of this "Gaussian" function, e^(-x^2 /5), over that domain. Hint: Make sure you plot x-y pairs and not just a list of y-values. Doing it correctly will result in a plot centered on the origin.

How to access individual list elements

Mathematica uses double square brackets to indicate specific list elements. (This is technically a shortcut for the Part function.) For example:

grocerylist = {"eggs","milk","bread", "soda", "ice cream"}

grocerylist[[2]]

grocerylist[[5]]

grocerylist[5]   (* wrong way!! *)

Things to observe:
1. This is a list of a new type of data, called strings. A string is just a collection of text characters formed into a word or phrase.  
2. If you accidentally try to access a list element using single square brackets instead of double, Mathematica will be very confused. In the example labeled “wrong way”, it thinks that you want to evaluate the grocerylist function at x=5. But no such function exists, so it is unable to comply with the request and spits out a garbage answer. Be very careful to use double square brackets to refer to list items.

Replacing a list item: You can also use this double square bracket notation to replace a specific list item.

grocerylist[[2]] = "lowfat milk"

grocerylist

Some basic list functions

Here are some of the most useful functions involving list manipulation.

grocerylist   (* reminder *)

Length[grocerylist]

Reverse[grocerylist]   (* reverses order *)

Sort[grocerylist]

Append[grocerylist, "steak"]  (* adds to the end *)

Insert[grocerylist, "candy", 3]   (* inserts into position 3 *)

Drop[grocerylist,2]  (* drops 2 items from the start of list *)

Drop[grocerylist,-3]  (* drops 3 items from the end of list *)

ReplacePart[grocerylist, 4-> "root beer"]  (* replaces the fourth element of the list *)

grades={90,76,88,45,99,86,76,85,97,99}
Sort[grades]
Sort[grades,Greater]

Select[grades, #>90&]

Things to notice:

1. Length tells you how many items are in the list.

2. Sort puts the list items in alphabetical or numerical order. You can specify details about how to sort (e.g. low to high vs high to low); see help file for details.

3. Reverse, Append, Insert, and Drop are all fairly obvious. 

4. ReplacePart used this way is identical to more simply stating:  grocerylist[[4]] = “root beer”.  But it has some added features relating to replacing multiple items at once which can be helpful.

5. Select allows you to determine which list items meet a particular criterion. In the example given here, I specified the criterion using an unnamed function which compared the numbers in the list to the number 90.

Beyond one dimension--2D lists

We’ve seen how to do lists of numbers... but some of the ListPlot examples above used lists of pairs of numbers. Since each pair is a two-element list, a list of pairs involves a “list of lists”. That is, a list in whcih each element is itself a list. 

Here’s another example of a list of pairs. These are two equivalent commands that generate a series of (x,y) pairs of points for the y = sin(x) function in steps of 0.2.

pairs ={#, Sin[#]}& /@ Range[0,10,.2]   (* The /@ command is a lot like the @ command, and is explaned more below in the "Using "Map" on a list of lists" section *)

pairs=Table[{x,Sin[x]},{x,0,10,.2}]

We can plot the points if we want:

ListPlot[pairs]

You can visualize how these numbers are organized by using MatrixForm and/or TableForm to look at the lists.

pairs //MatrixForm

pairs//TableForm

When viewed that way, it should be obvious as to why a list of lists is often called a two-dimensional list (or equivalently, a two-dimensional “array”). It requires two numbers, called indices, to specify the list elements--one for the row, and one for the column.

pairs[[5,2]] (* the element in 5th row, 2nd column *)

pairs[[5]] (* this just gives the fifth row *)

pairs[[5]][[2]]  (* another way of accessing the number in the 5th row, second column *)

Things to notice:

1. Make sure that the pairs[[5,2]] command actually gives the number in the 5th row, 2nd column. 

2. The (5,2) list element can be accessed via either [[5]][[2]] or [[5,2]]. Personally I prefer the latter but I think the former may be more common. I believe that’s because Mathematica didn’t originally allow the latter notation, but I could be wrong. I’ll use the two interchangeably.

The commands which generate 1D lists can generally be used to generate 2D lists as well. For example, here's a 2D list generated by the Table command:

twoDlist = Table[x y^2,{x,-5,5}, {y,-4,4}]

twoDlist//TableForm

Length[%]

twoDlist[[3]][[3]]

Things to notice:

1. This Table command created a 2D list that’s somewhat similar to the function f(x,y) = x y^2. The first index specifies which of the x-values you want to query, the second index specifies which of the y-values. If you look closely, you can see that it’s really an 11 element “list of lists”, where each element in the list is its own 9 element list. That’s why Mathematica reports its length as 11. Similarly, when viewed in TableForm (or MatrixForm), you can easily tell there are 11 rows.

2. Find -12 in the list and make sure you understand why it was the answer to the last command.

Assignment 6. A series of list functions

Start with list1 = {{4,8,9,10},{8,6,7,1}} and list2 = {{3,7,8,4},{3,1,2,8}}. Join the two lists together, then Flatten the resulting list, Sort in ascending order, find the Union (i.e. the unique elements), use Complement to extract only those elements that are not equal to 1, 2, or 3, Reverse the order, then finally Partition the result into pairs.  If done correctly, this exercise yields  {{10, 9}, {8, 7}, {6, 4}}.    (You'll need to read up on Join, Union, and Complement on  your own.)

3D lists

If a 2D list is like a matrix, a 3D list is like a set of matrices, each matrix indexed by its own number. You visualize them as matrices written on pages in a book, one matrix per page: the first number tells you which page, then the second and third numbers tell you which row & column to go to when you get to that particular page. This is an example of a 2x3x2 list with 12 total elements: 2 pages, 3 rows, and 2 columns.

threeDlist = {{{"this","is"},{"a","very"},{"inconvenient","way"}},{{"to","generate"}, {"a", "three"}, {"dimensional", "list"}}}

Dimensions[threeDlist]

Length[threeDlist]   (* how many "pages" *)

threeDlist[[1]] 
threeDlist[[1]]  // MatrixForm (* the first page *)

threeDlist[[2]] 
threeDlist[[2]]  // MatrixForm (* the second page *)

threeDlist[[1]][[1]]   (* the first row of the matrix on the first page *)

threeDlist[[2,3,1]]   (* the word that's on the second page, third row, first column *)

MatrixForm[threeDlist]   (* another way to display the info *)

Flatten[threeDlist];  (* now a 1D list *)
ReplacePart[%,10->"two"];
Partition[%, 2]   (* now 2D *)

Things to notice:

1. “threeDlist” is a list of lists of lists. In this case the main list is of length 2. That is, there are two elements, each of which is a list of lists. For example, the first element is this: {{this,is},{a,very},{inconvenient,way}}

2. Each of the two main elements is a three item list... each item of which is itself a two item list. For example, the first element of the first element is {this,is}. 

3. The word “dimensional” is in the second element of the main list (the bottom half of the MatrixForm output). It’s the third element of the bottom half. And it’s the first element of that list. Or you can think of it as the word on the second page, third row, first column. So the reference to that word is [[2,3,1]] or [[2]][[3]][[1]].

4. Using MatrixForm on higher dimensions than 2D can cause strange results. In particular the pages here are displayed as rows and the rows are displayed as columns.

5. Flatten used that way will turn any higher dimensional list into a 1D list. It can also be used to only partially flatten a list; see help file for details. Use carefully. 

6. Partition will turn a 1D list into a higher dimensional list. Use carefully.

Matrices

Basic matrix and vector operations

Because 2D lists are so very closely related to matrices, Mathematica just uses 2D lists directly for matrix and vector computation. If you haven’t seen matrices before you’ll get a chance to learn a lot more about them in a linear algebra class and in the Linear Algebra lab in this class. For now just think of a matrix as being a  2D list of numbers. You can add or subtract matrices if they have the same dimensions, and you can multiply them together under certain circumstances. Multiplying matrices is a lot more complicated than just multiplying the individual numbers together, however. The inverse of a matrix is the matrix which, when multiplying your starting matrix, produces an “identity” matrix (1’s down the diagonal and 0’s everywhere else). Mathematica has various built-in matrix-specific functions such as “take the inverse of a matrix” (which results in another matrix), or “compute the determinant of a matrix” (which results in a single number). Some of these are illustrated below. 3×3 matrices are closely related to three-component vectors (such as used in Physics 121), and such a matrix can multiply a vector, resulting in a new vector.

m = {{1,2,3},{4,5,6},{7,8,10}};   (* Define matrices like this *)
MatrixForm[%]

m2 = {{1,2,3},{4,5,6},{7,8,10}} //MatrixForm   (* Don't define matrices this way!! See below. *)

Transpose[m] //MatrixForm   (* Transpose switches the rows and columns of the matrix. It's OK to use MatrixForm in postfix as long are you are not defining anything *)

Det[m]  (* computes the determinant *)

minverse = Inverse[m];   (* This is the matrix inverse of m, often written as m^-1 in textbooks *)
MatrixForm[%]

m^-1;
%//MatrixForm   (* This is not the matrix inverse! *)

v = {3,-2,1};    (* this is a vector *)
MatrixForm[%]

m.v //MatrixForm   (* This is m times v, using matrix multiplication *)

m * v //MatrixForm  (* This is not m times v! *)

Warning:  There is a very subtle difference between the matrix itself (the 2D list) and the MatrixForm representation of the matrix. Defining a matrix like I did with m, and immediately viewing it via MatrixForm is a great idea. Defining a matrix like I did with m2, while also simultaneously using //MatrixForm to force it into the MaxtrixForm representation is a bad idea. Don’t do that! It defines m2 to be the MatrixForm representation of the actual matrix, which won’t always behave as the matrix itself should. (But if you’re not setting a variable equal to the matrix, there’s no problem with using  //MatrixForm at the end of your matrix commands.)

Other things to observe
1. Many matrix functions work as expected, such as Transpose and Det (determinant).  Also, Transpose can actually be used on any 2D list, not just a numerical-style matrix.
2. Many matrix functions do not work as expected. Specifically:  m^-1 does NOT calculate the matrix inverse. (It creates a new matrix where each element is the inverse of the corresponding element of the previous matrix. Not too helpful, usually.) And  *  does NOT multiply two matrices together using matrix multiplication. You must use a period for that, as in m.v. 
3. You can define row/column vectors as 1D lists like this: v = {3,-2,1}.  Mathematica will interpret it as either a row or a column depending on the situation.

More on vectors: You can do vector dot products and cross products, calculate the magnitude of a vector, and even create a unit vector in the same direction as the given vector:

v2 = {1,2,3};
MatrixForm[%]

v.v2

Dot[v,v2]

v\[Cross]v2 //MatrixForm

Cross[v,v2] //MatrixForm

Norm[v]

Normalize[v] //MatrixForm  (* creates a unit vector *)

v/Norm[v]  //MatrixForm  (* same thing, since a unit vector = vector/magnitude *)

Things to observe:
1. Dot products can be done with a period, like matrix multiplication.
2. There are many ways to produce the × symbol for cross product. Here are three:
	a. You can copy & paste an existing one.
	b. You can go to Insert→Special Characters→Symbols→Times menu. It’s labeled “cross”, not “times”, though.
	c. You can type the keyboard shortcut using the word “cross”: <Esc>cross<Esc>.  There are a number of shortcuts like that--for instance, to get Greek letters you typically can do <esc>name_of_letter<esc>. 
3. Norm gives you the magnitude of a vector (via Pythagorean theorem). Normalize creates a unit vector by dividing a vector by its magnitude.

More on Matrices:

Sometimes identity matrices are helpful.

IdentityMatrix[4] //MatrixForm

Calculating eigenvalues and eigenvectors are two of the most important things to do with matrices. If you don’t yet know about eigenvalues/eigenvectors, be patient. They arise in a large number of physics applications, so you’ll see them eventually. The output of Mathematica’s Eigenvalues and Eigenvectors commands can be a little funny, but the N command can usually clean things up.

Eigenvalues[m]

% //N

Eigenvectors[m]

% //N

% //MatrixForm     (* each row of this matrix is one of the eigenvectors *)

Assignment 7.  Solving for a vector

Let A = (({{3, 2, -4}, {2, 1, -2}, {4, 2, -5}}))and w = (({{1}, {2}, {1}})). Solve the matrix equation, A β = w  for the unknown vector β, and display it via MatrixForm. Hint: multiply both sides by the inverse of A.

Statistics

Basic statistical functions

I think these are all self explanatory.

yAL = {20,14,9,-4,7, 7};  (* stands for yetAnotherList *)
Min[yAL]

Max[yAL]

Mean[yAL] //N

StandardDeviation[yAL] //N

Median[yAL]

Commonest[yAL]   (* the mode *)

Total[yAL]   (* the sum *)

Total[yAL^2]  (* the sum of squares *)

Advanced statistical functions

The ability to generate random numbers can sometimes be helpful. There are two main Mathematica commands for that:

RandomInteger[6]    (* integer from 0 to 6 *)

RandomInteger[{14,46}]  (* integer from 14 to 46 *)

RandomInteger[{-5,5},20]  (* a list of 20 random integers from -5 to 5 *)

RandomReal[]   (* real number from 0 to 1 *)

RandomReal[{8.4, 13.7},10]  (* a list of 10 random real numbers between 8.4 amd 13.7 *)

Things to notice:

1. You can use each command in several different variations. Some of the most common are here. Look up the help files to see more examples.

2. These functions assume an equal probability for numbers across the entire range. That’s called a “uniform distribution”, and is not always what you’d like--for example, sometimes numbers in the middle should be more likely.

Nonuniform distributions. There are many built-in nonuniform distributions. One of the most useful is the “normal” (or “Gaussian”) distribution, which weights points in the center of the distribution more heavily than points on the edges. In other words, points near the center are more likely to be selected in a random draw. It has the form of  exp(-((((x-(OverBar[x])))^2)/(2(σ^2)))), where (OverBar[x]) is the center (also the mean) and σ is the standard deviation. So, for the Gaussian function used above in the ListPlot assignment, e^(-x^2 /5), the center is x=0 and the standard deviation is about 1.581  (=sqrt(5/2)). To get a random number weighted with a Gaussian distribution, you just change the first parameter of the RandomReal function call:

nsample = RandomReal[NormalDistribution[0,Sqrt[5/2]],50000];   (* 50000 random numbers... *)
Mean[nsample]     (* ...whose average is very close to 0... *)
StandardDeviation[nsample]  (* ... and whose standard deviation is very close to sqrt(5/2)  *)
Histogram[nsample]   (* to help visualize the list of numbers *)

Things to notice: The histogram of these random points is very similar in shape to our previous plot of the e^(-x^2/5) function.

Assignment 8. How to generate test data

When preparing to analyze experimental data it’s often useful to have a set of test data for testing your algorithms. To create some test data that mimics a noisy sinusoidal response, create a list of sin(x) values where x varies from x=-10 to 10 in steps of 0.1, and a list of random numbers (from -0.1 to 0.1, uniformly distributed). Then add these two lists together to create a “noisy” sin(x) function, and plot this function as a function of x (e.g. {x,function} pairs). Hint: You should have 201 values in your list.

Using “Map” On A List Of Lists

Sometimes you might want to use a “list of lists” as a matrix, but sometimes you might just want it to be just a collection of lists. A list of lists can be useful if you want to apply the same function to a bunch of lists, all at the same time. For example, here’s a “list function” I created which takes a list and returns the list with the average subtracted from each element:

subtractmean[x_] = x - Mean[x]

Let's test it out:

testlist1={1.1,2.2,3.3,3.4,3.5};
subtractmean[testlist1]

We mentioned above how you can use prefix notation to apply the same function to a list of numbers, such as this example with the function sin(x^2):

Sin[#^2] &    @  {0.1,0.2,0.3,0.4}

You might expect the same sort of thing to work for a list function such as “subtractmean”. However, observe what happens:

testlist2={1.3,2.7,3.5,3.9,4.5};
testlist3={1.7,2.9,3.8,4.4,5.5};
subtractmean[#]&   @{testlist1,testlist2,testlist3}

It crashes and burns. Other times when you attempt this, it might give you numerical values which are NOT what you are expecting. For example, if you try to determine the Mean of the three lists using the @ sign in this fashion, you get more than three numbers, so it’s obviously not returning a list of of the three means:

Mean[#]&   @{testlist1,testlist2,testlist3}

The solution: When you want to apply a function to each list contained within a list of lists, you must use the Map function, shortcut /@. You use the shortcut in exactly the same way that you would normally use the sample @ in prefix notation. For the subtractmean and the Mean examples, here’s what happens:

subtractmean[#]&   /@{testlist1,testlist2,testlist3}   (* gives you the correct three new lists *)
Mean[#]&   /@{testlist1,testlist2,testlist3}  (* gives you a list of the three means *)

Map is useful in some other contexts, and you will likely use it a lot this semester. For example, it was the first method that came to my mind for generating the x-y pairs in the “Beyond one dimension--2D lists” section above.

Bottom line: For now just realize that if using @ doesn’t generate the output you expect, try using /@ instead. In fact, I can’t offhand think of any times when using /@ would give you the wrong answer, even if @ is really what you should use--so I myself typically just always use /@  and not @ when I combine nameless functions with prefix form.

Function Arguments: Specifying Variable Types

Continuing on with the subtractmean function from the last section: subtractmean’s sole purpose in life is to do something to a list. If you attempt to use it on a number, it crashes and burns:

subtractmean[1]

One option you can use is to specify the type of variable when you define the function itself. That is, we can make it so that Mathematica will not even try to use the subtractmean function unless we give it a list. We do that by specifying a variable type such as Integer, Real, List, Symbol, etc., right after the underscore in the function definition.

newsubtractmean[x_List] = x - Mean[x]

The newsubtractmean function continues to work on lists as usual...

newsubtractmean[{1.1,2,3,4,5,5.9}]

...but it doesn’t even attempt to do anything (and consequently doesn’t generate an error message) when you give it an argument that is not a list.

newsubtractmean[1]

You can use this type of variable specification whenever you define a function. You can even use it to create a function that handles different types of variables very differently. For example, this function squares the argument if it’s an integer, and cubes it if the argument is a real number:

fspecial[x_Integer]:= x^2
fspecial[x_Real]:= x^3
fspecial[2]
fspecial[2.]  (* the decimal point after "2" causes Mathematica to treat it as a non-integer *)

Behind The Curtain: InputForm, FullForm, And TreeForm

“Form” commands

First click here to go to the tutorial on Expressions; try to understand what it means to say that “everything in Mathematica is an expression”.

The various “Form” commands can be useful for visualizing expressions in alternate ways. We saw two examples of that above, with MatrixForm and TableForm. Three other Form commands are InputForm, MatrixForm, and TableForm.

InputForm shows you what the command would have looked like, had it been inputted in standard notation. Among other things, it gets rid of any postfix and prefix options. With FullForm, you get to see what Mathematica does to your shorthand expressions before evaluating them.  TreeForm provides a graphical illustration of the order in which various operations are executed and allows you to interactively explore the intermediate values of the calculation.  

Consider the following basic calculation and conversion to decimal number.

6*(2^4+6/7^3-9+Pi/2)^2 //N

Let’s look at that expression using those three different tools. We have to use the Hold command in conjuction with them to prevent the numerical value from being calculated.

Hold[6*(2^4+6/7^3-9+Pi/2)^2//N]//InputForm

Hold[6*(2^4+6/7^3-9+Pi/2)^2//N]//FullForm

Hold[6*(2^4+6/7^3-9+Pi/2)^2//N]//TreeForm

Things to observe:
1. For the InputForm command, notice that N is no longer in postfix form.
2. For the FullForm command, notice how all operations that Mathematica must perform are explicitly spelled out. 
3. For the TreeForm command, notice how the order of operations is much easier to see than in the FullForm command.
4. Move the mouse over some of the boxes in the TreeForm output, and see how the intermediate calculations get displayed.

Expressions as lists

Expressions can also be viewed as lists, allowing you to “reach inside” them to extract or modify specific pieces.

example = a^2  + b + 1/(2+ 3^c)
example[[1]]
example[[1,1]]
example[[1,1,2]]
example[[1,1,2,2]]
ReplacePart[example,r,{1,1,2,2}]

Things to observe:  Be sure to understand why the exponent “c” from the original expression is considered the (1,1,2,2) list element for the expression. Viewing the expression in TreeForm may be helpful:

example//TreeForm

Additional Assignments

Assignment 9. Using FindRoot to solve a transcendental equation... and using the result

Let x0 represent the value of x for which x = e^-x. It is called a transcendental equation. Determine x0 with FindRoot, and then calculate sin(x0) without using any "copy and paste"ing (i.e. use slash-dot as detailed above). Hint: when solving transcendental equations it's always good to start with a graph of the functions that represent the left and right hand sides of the equation, to give you a rough idea of the answer. The solution x0 is where the functions intersect, because that’s the place where the left and right hand sides of the equation equal each other.

Assignment 10. Manipulating data

Download the file Th000088.txt into the same directory as where you have this noteboook saved. (The file is located on the department Physics 230 website.) Open it with a text editor to see what it looks like. It contains reflectance data from a thin film of thorium taken at the Advanced Light Source at Lawrence Berkeley Labs. Then read the file into this notebook using the following Import command:

SetDirectory[NotebookDirectory[]]
tdata = Import["Th000088.txt","Table"]

You’ll note that the data contains a header list followed by lists of four numbers.  These represent the wavelength of the beam, the measured reflected signal, and two other numbers which are not needed in this exercise.  Extract the wavelength and signal numbers and plot them using ListLogPlot.

Wrap-up

The following functions were discussed in today' s lab, or are very closely related:
Advanced function definitions: -> or -> (Rule), /. (ReplaceAll), := (SetDelayed), //  (Postfix), @ (Prefix), # (Slot), & (Function), pure functions 
Creating lists: Range, Table, Array
Plotting lists: ListPlot
List functions: [[ ]] (Part), Transpose, Length, Reverse, Sort, Append, Insert, Drop, ReplacePart, Select, Flatten, Join, Union, Complement, Partition
Vector/matrix-related list functions: MatrixForm, Det, Inverse, . (Dot, for dot products and matrix multiplication), × (Cross for vector cross products), Norm, Normalize, IdentityMatrix, Eigenvalues, Eigenvectors
Statistics-related functions: Min, Max, Mean, StandardDeviation, Median, Commonest, Total, RandomInteger, RandomReal, Histogram, NormalDistribution
To apply a function to a group of lists: /@ (Map)
Algebraic functions: Expand, Together, Apart, Collect 
Misc: Degree, Exp, Series
Viewing Mathematica’s insides: Hold, FullForm, and TreeForm

Potentially useful summary/tutorial pages
Guide: Special Characters
Tutorial: Strings and Characters Overview
Tutorial: Pure Functions 
Guide: Constructing Lists
Guide: Elements of Lists
Guide: List Manipulation
Tutorial: Testing and Searching List Elements
Guide: Constructing Matrices
Tutorial: Vectors and Matrices
Tutorial: Basic Matrix Operations
Guide: Parametric Statistical Distributions
Tutorial: Expressions