Creating and Plotting Lists

Math 242 Modern Computational Math, spring 2021

Today we will learn about some Mathematica functions for creating lists.

First, let's define a simple module with an accumulator. We just need something that will return values that we can put into a list. The following module returns the sum 1+2+3+⋯+n.

mySum[n_]:=Module[{sum=0},
Do[sum += i, {i,1,n}];
sum
]

Range

The Range function gives a list of integers:

Range[10]

You can specify the start and stop values:

Range[4,10]

You can also specify the step size:

Range[4,20,3]

Table

Recall that we can make a list with the Table function.

Table[ mySum[n],{n,1,10}]

Table is useful when we want to specify the index set that is used to create the list.

Map

The Map function is similar to Table, but more concise. Specifically, the following syntax evaluates a function on a specified list, returning a new list of the results.

Map[function, list]

Here is an example:

Map[ mySum,{3,4,5,6}]

Map also has a shorthand operator:

mySum /@ Range[10]

ListPlot

Plotting a list is easy with ListPlot:

myList=mySum/@Range[10]

ListPlot[myList]

It's good practice to label your plot and your axes. Here is how to do it:

ListPlot[myList,PlotLabel->"A cool plot",AxesLabel->{"n","sum"}]

Indexed Variables

Suppose that you are working with variables that have subscript indexes. (For example, in the Salamin and Brent algorithm!) While Mathematica lets you define variables with subscripts, it’s usually better to use indexes in square brackets.

For example, suppose you want to define (Subscript[a, 1])=4 and (Subscript[a, k])=(Subscript[a, k-1])+2 for k=2,3,...,10.

a[1]=4
Do[a[k]=a[k-1]+2,{k,2,10}]

Now you can access the values like this:

a[3]

You can use function like Map to create a list from your indexed value:

a/@Range[10]

You can also query the symbol a to find out all of the indexes that are defined:

?a

Inside of a module, you only need to put the symbol a in your local variable list, and all of its indexed values will be local. Here is a simple module that illustrates this:

testModule[n_]:=Module[{a},                  (* a is a local variable *)
a[1]=4;                                                            (* an indexed value *)
Do[a[k]=a[k-1]+2,{k,2,n}];      (* a loop that stores more indexed values *)
a[n]                                                                       (* return a[n] *)
]

Try it out:

testModule[14]