Mathematica Shortcuts and Modifying Lists

Math 213 - Math with Mathematica
Christopher Hanusa

Aim

This tutorial first starts off with some best practices for Mathematica, and some shortcuts to make your life with Mathematica easier.  Then we develop tools for creating, accessing, and modifying lists.

Tip: You can evaluate ALL cells in this file in order using the Evaluation > Evaluate Notebook command.

NOT losing your work

Save your work

Mathematica is more likely to crash than other programs you’re used to, especially when you’re in the middle of a complex computation, or when it is right before your project is due.  Save your notebooks frequently.

AutoSave!

It is possible to turn on the AutoSave feature of Mathematica.  What it will do is save your work every time you do an evaluation. (Shift-Return)  Follow these steps to turn it on:

Go to Preferences > Advanced

Click on “Open Option Inspector”

Ensure that “Global Preferences” is selected in the “Scope” pulldown menu.

In the Search Bar type in AutoSave

Click the checkbox next to “NotebookAutoSave”.

The only problem I have found with enabling AutoSave is that it slows down your coding process because it makes the computer work more often.  The piece of mind you get from knowing that your work is being saved regularly is worth it.  If things really start to go very slowly, it’s probably because your notebook is very very large.  When this happens to me, I save my work, I open a new notebook and bring over the most essential pieces of code into the new notebook and work from there.

Undo

Mathematica has an undo command (Ctrl-Z or Option-Z is the keyboard shortcut). BUT it doesn’t always work, and don’t depend on it being able to undo more than one thing.

Incremental Development

One way to avoid using an Undo command and that is a good programming practice that you should start to use is incremental development.  It boils down to three principles:

Always start with a piece of working code.

Make only one small modification at a time.

Test the new code to see if the change worked.

This is helpful because if you change something small and it breaks, it’s easy to find.  On the other hand, if you try to write a piece of code that is complex all in one go, then if it doesn’t work it will be much harder to find your error.

In a Mathematica notebook, the best way to do this is to start with a “Minimal Working Example”, such as a piece of code from the Documentation Center.  Then as you build your code and it becomes more and more complex:

Copy a piece of code that is working the way you want it to into a new cell just underneath.

Modify the code in the new cell in a new way.

Run the code in the new cell to see if it does what you want it to.  If so, repeat the cycle.  If not, check to see where it went wrong.

Cloud Storage

It is good practice to save your work in multiple places so that you won’t lose your work if your computer dies.  One good way to do this is to use cloud storage.  Three good versions are Dropbox, Google Drive (available as part of the QC Google Apps for Education), and Microsoft OneDrive (available as part of your QMail account).  You should create an account on one of these services and make sure to upload your files to them.  In this way you will have access to them anywhere there is internet. If you have questions about this see me.

Defining variables using the = operator

It is often helpful to define the output of a command to be able to reuse it later.  To do this, use the = operator:

a=Range[3]

a

If you don’t want to see the output of a command, you can end the line with a semicolon.

a=Range[4];

a

Important: it matters the order in which you evaluate commands.  For example, if you re-evaluate the first instance of a, it will return its last-defined definition, which is {1,2,3,4}.

I HIGHLY suggest that you give descriptive names to your variables. Since all built-in Mathematica commands start with a capital letter, a nice convention to use for your own variable names is to start with a lowercase letter and if variable is multiple words long, capitalize the start of each new word.

iAmANewVariable=Range[Pi,2Pi,Pi/2]

heyYouWhatsThatSound=Play[Sin[440 2Pi t],{t,0,1}]

(OK, the provided example names aren’t very descriptive, but you get the idea....it’s #likeAHashtag.)

Shortcut: the % operator

A useful but slightly dangerous operator is %, which stands for the most recent output.  So, for instance, if you decide to make a list, and then decide you want to create a scatterplot, you can do the following:

Table[RandomInteger[{1,3}],{100}]

ListPlot[%]

The reason it is dangerous is related to the above discussion where the order in which you evaluate commands matters.  If you tried to re-evaluate the previous line of code, you would get an error, because you can’t create a scatterplot of a scatterplot!

ListPlot[%]

In the same vein is %% (for two outputs back); slightly more safe might be Out[n] to be explicit about wanting the nth output.  (But this will depend on the session in which you are working, so it would be different each time you re-open your notebook!!!!)  It is best to define a new variable when you think you will be using the output later.

When you’ve gotten yourself in trouble

When you don’t understand a command.

By now you should know that you can search in the Documentation Center when you want more information about a command.  You can also get quick information about a command directly in a Mathematica notebook by using the ? operator.

?Tally

Notice the >> symbol at the end of the command information.  Click there to go directly to the Documentation Center.

You can also hover over a command to open up this quick command information or to go directly to the Documentation Center.

When you define something you shouldn’t have.

Suppose you define a variable at some point:

x=10

Perhaps later in your file you wanted to generate the list {x+1,x+2,x+3} using the Table command:

Table[x+i,{i,3}]

Since x had been defined before, the generated list has no x’s in it.  When you run into such a problem, you use the Remove command:

Remove[x];
Table[x+i,{i,3}]

When your code won’t stop running

We all get into infinite loops sometimes.  To stop Mathematica in the middle of a calculation, use (Option-.) or (Alt-.)  (That’s the period!)  
Try it here after removing the (* and *) which I used to comment out the command.

(* For[i=0,i≥0,i++,i] *)

Comprehension Questions:

1. Practice using the % operator.  
First, define some list of even numbers by way of a Range or Table command.  
Then use % to divide the list by 2 to divide each entry by 2.  
Then use % to add 10 to each entry of the list.
Last use % to give a scatterplot of this final list.

2. Use the ? operator to learn about the commands First and Rest.

The Table command, Part Deux

More Variables

The Table command can also create a list with two or more variables changing at a time.  Simply put two variable ranges as inputs.  In the following example, we consider all values of x from 1 to 3 and all values of y from 1 to 3 and multiply them together (because that's what the function x*y says to do).

array=Table[x*y,{x,3},{y,3}]

I would read this line of code as “Create a table of values of x times y, where x ranges from 1 to 3 and y ranges from 1 to 3, and define the result to be called ‘array’.”

More Complicated Functions

The Table command is much more powerful than simply creating lists of numbers.  For instance, you can create lists of anything in the language of Mathematica:

Graphics objects:

Table[Plot[x^n,{x,-2,2}],{n,0,10}]

Coordinates of the vertices of a hexagon:

Table[{Cos[2π k/6],Sin[2π k/6]},{k,0,5}]
Graphics[Polygon[%]]

Pictures of polygons:

Table[Graphics[Polygon[Table[{Cos[2π k/i],Sin[2π k/i]},{k,0,i-1}]]],{i,3,10}]

Colors:

Table[ColorData["Rainbow"][x],{x,0,1,.1}]

The Periodic Table of the Elements:

Table[ElementData[i,"Abbreviation"],{i,1,100}]

Comprehension Questions:

3. For each of the following Table commands, complete the following sub-questions.
(a) BEFORE EVALUATING THE COMMAND, what list do you expect the command to give?  Or do you expect an error?
(b) Now, evaluate the command.  Did it do what you expect it to do?
(c) If not, figure out what went wrong with your reasoning.

Table[{s,7,9},{t,3,5}]

Table[{x,y},{x,2,4},{y,5,7}]

Table[xy,{x,2,4},{y,5,7}]

Table[Plot[x^n,{n,-2,2}],{x,1,10}]

Table[CountryData[country,"Population"],{country,{"France","United States","China"}}]

4. Determine which Table commands give the following lists.  There are multiple solutions for each one.

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

{{{0,0},{0,1},{0,2}},
{{1,0},{1,1},{1,2}},
{{2,0},{2,1},{2,2}}}

{{5,5,5},{6,6,6},{7,7,7},{8,8,8},{9,9,9},{10,10,10}}

{{"France","has",(Quantity[64101308, "people", people, "People"])},{"United States","has",(Quantity[322422965, "people", people, "People"])},{"China","has",(Quantity[1364773138, "people", people, "People"])}}

Solutions

Table[Range[i],{i,5}]

Table[{i,j},{i,0,2},{j,0,2}]

Table[{i,i,i},{i,5,10}]

Table[{country,"has",CountryData[country,"Population"]},{country,{"France","United States","China"}}]

Challenge Questions

5. Determine which Table commands give the following lists.

{{B,(B^2),(B^3)},{A B,A (B^2),A (B^3)},{(A^2) B,(A^2) (B^2),(A^2) (B^3)},{(A^3) B,(A^3) (B^2),(A^3) (B^3)},{(A^4) B,(A^4) (B^2),(A^4) (B^3)}}

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

{,,,,,,,,,,}

Useful list commands

Flatten

When there are nested lists and you would like to remove some of the extra braces, you should use Flatten.

list=Table[x*y,{x,3},{y,3}]

Flatten[list]

You can also specify how many layers of braces you want to remove.  For example, if your goal is to create a set of coordinate pairs (for points on a picture, for instance), then you wouldn’t want to remove all of the braces.

list2=Table[{x,y},{x,3},{y,3}]

Flatten[list2]

Instead, use the optional second argument to only remove one set of braces.

Flatten[list2,1]

Prepend and Append

When you want to add elements to the end of a preexisting list, use Append.  To add elements to the beginning, use Prepend.
This is often used in conjunction with redefining the preexisting list.

powersOfTen=Table[10^i,{i,0,5}]

Append[powersOfTen,10^6]

powersOfTen

Prepend[powersOfTen,0]

You can see that powersOfTen does not change when using Append or Prepend. 
You need to redefine powersOfTen if you want to actually add an entry to the list for future use.

powersOfTen=Append[powersOfTen,10^6]

powersOfTen

Comprehension Questions:

5. For each of the following commands, complete the following sub-questions.
(a) What list do you expect the command to give?  Or do you expect an error?
(b) Now evaluate the command.  Did it do what you expect it to do?
(c) If not, figure out what went wrong with your reasoning.

Flatten[{{{{1},2},3},4}]

Flatten[{{{{1},2},3},4},2]

Append[{1,2,3,4},{1}]

Append[{{1,2},{3,4}},5,6]

Append[{{1,2},{3,4}},{5,6}]

Discuss these answers with your neighbors.

6. Consider rolling two dice and taking the sum of the values.  What is the average value for this sum?  What is the average value for the product of two rolled dice?  Three rolled dice?  Four?

Accessing parts of lists

One entry of a list

It is often useful to access one or more of the entries of a list.  For this we use double square brackets [[n]], which is the shorthand notation for the command Part.

powersOfTen[[5]]

Part[powersOfTen,5]

One entry of an array

When the list is a nested list, you can reference an entry of the list to choose a sublist, or any entry of any sublist.

nestedList={{1,2},{3,4},{5,6}};

nestedList[[2]]

nestedList[[2,1]]

Multiple entries of a list

To extract multiple entries from a list, you can put a list of indices in the double square brackets.

powersOfTen[[{3,5}]]

powersOfTen[[Range[3,5]]]

Multiple entries of an array

To choose certain rows and columns of an array you can also use sets.  If you want all of the rows and only some of the columns (or vice versa), use the variable “All”.

products=Table[x*y^2,{x,1,10},{y,1,10}];
TableForm[products]

Here we choose rows three, four and five, and columns 2, 4, and 8:

products[[Range[3,5],{2,4,8}]]

Here we choose the second entries of every row:

products[[All,2]]

Comprehension Questions:

7. Write the code that takes entries 5 through 15 of this list primes

primes=Table[Prime[n],{n,1,20}]

8. What code should you use to choose the odd entries of the variable powersOfTen?  Can you make it a general piece of code that works no matter how long the variable powersOfTen is?

9. Write the code that chooses the third entries of every column of products.

10. Here are two lists which represent the x- and y-coordinates of points, and an incorrect Table command that hopes to collect the points into a list of ordered x,y pairs.  Figure out what is wrong with the command and fix it.

x={1,2,3,4,5}
y={2,5,10,17,26}
points=Table[{x[i],y[i]},{i,1,Length[x]}]

Solution:

You need to use double brackets to reference parts of a list.

points=Table[{x[[i]],y[[i]]},{i,1,Length[x]}]

Exploration Question

11. Visit the Documentation Center entry for Getting Pieces Of Lists to see other commands Mathematica uses to take pieces of lists.  What does the ;; operator do?