Tutorial 2 -  List, Table, Array

1. List basic

1.1 General discussion

Sometimes, data is not just one single item, for example:

Variable “social network” is not just one thing, but a List of things. Likewise for variable “market share”. How do we represent such a variable?

marketshare={0.46,0.29,0.02,0.04,0.04,0.06,0.09};
socialnetwork={,,,,,,};

In other words, a List is a 1-dimensional array, formed by:  { , , , ,...} ; Note that the separator is , NOT semiconlon ;

One way to remember the separator syntax is this:  .csv: comma-separated value. In Mathematica, just like in C++, Python, semicolon ; is for terminating a statement.

There is another thing worth noticing: socialnetwork is a list of items, but each item is not a number, but an image. We will learn later on that Mathematica, like any other advanced language, deals with objects that can be anything as a single entity.

Another example, a grocery shopping List.

Variable “item” is the List of grocery item to be shopped, and variable “unit” is the List of number of units to be purchased.

Exercise 1.1

Define a variable groceryitem that contains data of the first column, and groceryunit that contains the data in the second column. Note that a variable value that is a string requires quotation mark, such as “storage bags”.

Answer

1.2 Compared with other languages

All programming languages that are at a higher level than Assembly language allow data structure of multiple items, known as “array”. Usually it is a sequential block of memory that can be addressed by a single variable name, and the index points to the content of the position in the memory block.

Example from C++:

In Mathematica, Python, R, and some other languages, we use array with a more elevated concept: List, which is an ordered set of objects that may allow mixing of different types of variables. But first, let’s compare the syntax. Similar to C++, Mathematica uses curly brackets: {}, unlike Python with [] (A most common habit twister when switching between Mathematica and Python is the [] and () ).

1.3 Generalized data and variables

Any object data (or data object) can be a named variable.

str="this is a string" ;
str

pict= ;
pict

Exercise 1.2

Use your computer webcam to take a picture of yourself and name “mypict”. If you don’t have one, just download from your phone or your social media page. The function to use is:

ImageCapture[]

After you capture an image, name it mypict, then verify you have it by calling mypict.

Answer (this is only an example - delete, replace with yours)

mypict=;
mypict

END exercise

Now, we will try a sound data object:

ltune=;

ltune

EmitSound @ ltune

Here we learn a syntax of Mathematica: instead of using [], we can also use @ (which means apply, such as applying the function to the variable. Example:

Sin[0.7]

Sin @ 0.7

Exercise 1.3 Record your student ID info

Use this function: SystemDialogInput[“RecordSound”] to record a sound object: “saying your name, and student ID” for example: “John Doe <pause>  0987654321”. Recommended setting: 22 kHz, 16-bit, mono.

myID=SystemDialogInput["RecordSound"]

then apply EmitSound[myID] to verify it you have the data.
Check with SpeechRecognize[myID]

An alternative function is AudioCapture[]

Answer

Exercise 1.4 Synthesize your spoken student ID

We can use function Speak to generate an immediate system sound, like this

Speak["John Doe, 0987654321"]

However, it doesn’t give us a sound object. We can use a different function SpeechSynthesize

However, we need to choose a voice style, check your computer voice styles:

$VoiceStyles

Now, define a variable for a string that contains your name and student ID. Then generate a speech based on that string named it myIDsynth

Answer (delete this example and replace with your answer).

mystr="Jane Doe, 0987654321";
myIDsynth=SpeechSynthesize[mystr,$VoiceStyles[[7]]]// Normal  ;

myIDsynth

EmitSound @ myIDsynth

1.4 List of different types of object: concept of record, database

mydata={"Doe","Jane","0987654321",,
,Hyperlink[,"https://www.ncbi.nlm.nih.gov/grc/human"] (* object can be executable *)
 , (* object can be an app *)};

mydata

Exercise 1.5 Create a list of your personal data as shown below

mydatarec={"your last\! name","last name", "student ID" ,"email" (* all are String *)
,(* image object: your selfie obtained earlier *)
, (* sound object: myID obtained above *)};

Answer (delete this example and replace with your answer)

mydatarec={"your last\! name","last name", "student ID" ,"email" (* all are String *)
,(* image object: your selfie obtained earlier *)
,  (* sound object: myID obtained above *)};

mydatarec

END exercise

Additional examples:

x1={a,2,b,w,9,0,"an array",}

x2={,,,,,}

x3={"south pacific",,}

1.5 Reference elements of a List

x2={,,,,,};
Manipulate[
x2[[n]]  (*  double square bracket  *)
,{n,{1,2,3,4,5,6}, ControlType-> SetterBar}]

One can embed the data inside a Manipulate object, so that one doesn’t have to execute statements outside or prior to the Manipulate object.

Manipulate[
x2[[n]]
,{n,{1,2,3,4,5,6}, ControlType-> SetterBar}
,Initialization:>{
x2={,,,,,};
}]

x2={,,,,,};
Manipulate[
pict
,{pict,x2, ControlType-> SetterBar}
]

Manipulate[
{x2[[n]],Speak[x2s[[n]]]}
,{n,{1,2,3,4,5,6}, ControlType-> SetterBar}
,Initialization:>{
x2={,,,,,};
x2s={"rock against the sky","beach with palm trees","winding canyon river","sunset on a lake","waterfall","autumn foliage on a lake"};
}]

2. Examples of using List objects

2.1 List - graphics example 1

Here, just to change the subject to make it more interesting, we’ll do some example in business, marketing instead of just engineering.

Let’s do this exercise: generate this graphics:

2.1.1 Step 1: data

marketshare={0.46,0.29,0.02,0.04,0.04,0.06,0.09};
socialnetwork={,,,,,,};

Below are equivalent examples in R (open cell to see  ->  )

we can make an array or simple list using c-function of R.

END R example - resume Mathematica lecture

2.1.2 Step 2: make a PieChart3D

Exercise 2.1 make a pie chart

Make a pie chart with given list data of market share above.

Answer

2.1.3 Step 3: make a PieChart3D with logos as legends

Exercise 2.2 pie chart with legends

Make a pie chart of market share data with logos as legends

Answer

2.1.4 Step 4: use alternate color

marketshare={0.46,0.29,0.02,0.04,0.04,0.06,0.09};
socialnetwork={,,,,,,};
color={Hue[0.6,1,0.5],Hue[0.54,0.7,1],Hue[0.6,0.5,1],Hue[0.75,0.7,1]
,Hue[0.08,1,1],Hue[0.35,0.7,1],Hue[0.,0.8,1]} ;

Exercise 2.3 pie chart with given color

Use option ChartStyle

Answer

END exercise

2.2 List - data tabulation example

2.2.1 Grid as a printout display

marketshare={0.46,0.29,0.02,0.04,0.04,0.06,0.09};
socialnetwork={,,,,,,};

Grid[{socialnetwork,marketshare}]

Grid[{socialnetwork,marketshare}, Frame-> All]

Grid[{socialnetwork,marketshare}, Frame-> All
,BaseStyle->{20,FontFamily->"Calibri"}]

Grid[{socialnetwork,marketshare}, Frame-> All
,BaseStyle->{20,FontFamily->"Calibri"}
,Background->{,{Hue[0.85,0.2,1],Hue[0.13,0.3,1]}}]

Grid[MapThread[Prepend,{{socialnetwork,marketshare},{"social network","market share"}}]
,Frame-> All, BaseStyle->{20,FontFamily->"Calibri"}
,Background->{{Hue[0.1,0.4,1],},{}}]

groceryitem={"juice","eggs","fruits","vegetables","milk","cereals","coffee","tea","ice cream","napkins","foils","storage bags","toothpaste","shampoo","detergent"};
groceryunit={3,4,12,8,2,6,1,2,3,5,2,10,4,3,2} ;

Grid[{groceryitem,groceryunit}, Frame-> All
,BaseStyle->{20,FontFamily->"Calibri"}
,Background->{,{Hue[0.85,0.2,1],Hue[0.13,0.3,1]}}]

Grid[Transpose[{groceryitem,groceryunit}], Frame-> All
,BaseStyle->{20,FontFamily->"Calibri"}
,Background->{,{Hue[0.85,0.2,1],Hue[0.13,0.3,1]}}]

Grid[Transpose[{groceryitem,groceryunit}], Frame-> All
,BaseStyle->{20,FontFamily->"Calibri"}
,Background->{{Hue[0.85,0.2,1],Hue[0.13,0.3,1]}, }]

Grid[Join[{{"item","unit"}},Transpose[{groceryitem,groceryunit}]]
,Frame-> All, BaseStyle->{20,FontFamily->"Calibri"}
,Background->{{},{Hue[0.35,0.3,1],}}]

Exercise 2.4 (answer given)

Find the logos of the following market indices: Dow-Jones, S&P, Nasdaq, FTSE, Nikkei, and Hang Seng and make a named list.

Answer (given)

marketindexicon={,,,,,};
marketindexicon

Exercise 2.5 (answer given)

Make a named list of the market symbols corresponding to the above.

Answer (given)

marketindList={"^DJI","^GSPC","^IXIC","^UKX","^NIK","^HSI"};
marketindList

Exercise 2.6 (answer given)

Make a dynamic Grid display of market index values whenever a button is pushed

Answer (given)

Manipulate[
If[TrueQ[RUNmarketindex== ],
Manipulate[
If[TrueQ[GETUPDATE] || !ListQ[marketindexvalue],
marketindexvalue=FinancialData[marketindList,Method->"Legacy"];
GETUPDATE=False
,];
Grid[{marketindexicon,marketindexvalue}
,Frame-> All
, Background->{{Hue[0.04,0.4,1],Hue[0.16,0.4,1],Hue[0.32,0.4,1],Hue[0.45,0.4,1],Hue[0.55,0.4,1],Hue[0.85,0.4,1]}
,{,GrayLevel[0.9]}}]
,Button[,GETUPDATE=True]] 

,Button[, RUNmarketindex=]]
,Control[{{RUNmarketindex,,},{,},ControlType-> Toggler}]
,Initialization:>{
marketindList={"^DJI","^GSPC","^IXIC","^UKX","^NIK","^HSI"};
marketindexicon={,,,,,};
}]

3. Table and Array

3.1 Basic concepts

All ordered set of items are called “list” in Mathematica. They can also be called “table” or “array” (generic concepts). It is convenient to generate a list from a formula or function. When we do this, the elements of the list are usually of the same types, for example, they can be numbers, strings, images, etc. Hence, there is really no fundamental difference between general “list” and “array”, except that the latter is usually used to imply that all elements have the same type.
Below, we use Table to generate a list that can be considered as one-dimensional array

Table["item to be generated",{i,1,10}]

Exercise 3.1

Generate a table, name it with a name of your choice, item generated is (index^2) for index from 0 to 20 in step of 1.

Answer

Exercise 3.2 ListPlot

Use ListPlot and ListLinePlot to plot your table data in 1.1 above. For  ListPlot, use this option:
PlotStyle-> {Red,PointSize[0.02]}
Put both graph into a list with a name (only one name for the list), then use Show[“the list name”]

Answer

Exercise 3.3 Damped oscillator

Consider this function:  s[t]=(e^(-t/τ)) Cos[2 π f t]; where t is time. Let τ=0.35 sec, f=440 Hz. Calculate s(t) for t=0 to 1 sec, in step of 1/11025 sec. (11025 is known as the sampling rate). 
- Make a ListPlot of the data
- Make a sound with array s(t) that you obtain.

Answer

END exercise

3.2 Range

We don’t always need to use Table to generate a most often used array: a linear array. For this we can also use Range.

Range[7]

Range[25]

What if we want to generate from -12 to 37?

Range[-12,37]

What if we want to generate from 0.8 to 3.6 in step of 0.12

Range[0.8,3.6,0.12]

ListPlot[Range[0.8,3.6,0.12]]

Ever since after Math 9, Mathematica Plot function can sometimes be very very slow. Hence, it is sometimes better to generate an array points to plot just like other languages. One can apply a function to a linear array:

xarray=Range[0.8,3.6,0.12];
Sin[xarray]

Exercise 3.4

Use this code to generate a 2D vector, you must provide values of coordinate x and y for each point below.

startpoint={x1,y1}; endpoint={x2,y2};
vector1=Arrow[{startpoint,endpoint}];
Graphics[{Blue,vector1}]

Answer

Exercise 3.5

Use the above code in Exc. 1.3 to generate an array of 48 vectors like this:
start point: {(n/16),0}  end point {(n/16),Sin[2 π (n/16)]} for n from 0 to 47. Do this by using Table that contains 48 vectors.

Answer

3.3 Table of Table: nested Table

In the above example. we have an array of vectors:

efield=Table[startpoint={x,0};endpoint={x,Sin[2 π x]}; (* note semicolons *)
Arrow[{startpoint,endpoint}],{x,0,(47/16.),(1/16.)}]; 
Graphics[{Blue,efield}]

Suppose the function of interest has another variable, t besides x, and it is not Sin[2 π x] but Sin[2 π (x-t)]. Then to show it for different values of t, we need another dimension: we have an array depending of x for each t value. What we need is a table of table: nested table.

Exercise 3.6

Create a table in which, each element is a graphic object of vector above, but let the function be Sin[2 π (x-t)]. The index of the outer table is t, for t from 0 to 1-(1/80), in step of (1/80). Name the created table, but don’t print out.

Answer

Exercise 3.7

Use Manipulate to show the (i^th) element of the list generated in Exc. 1.5.
Manipulate[ yourarray[[i]] , {i, 1 ,Length[ yourarray] , 1 }]

Answer

Exercise 3.8

Follow instruction in class.

Answer

Exercise 3.9 Damped oscillator - with different frequencies

Use nested Table to make a table of signals similar to 3.3, but different frequencies and durations: f = {261.63, 261.63, 392, 392, 440, 440, 392}, and for each frequency, the corresponding duration is: t={0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 1}. Then use Flatten to put all of them together into a single list and play.

Answer

END exercise

3.4 Referencing elements from a multi-D array

It is straight-forward similar to other languages. First, recall what we have with an example above

mydata={"Doe","Jane","0987654321",,};
First[mydata]
mydata[[1]]
Last[mydata]
mydata[[4]]

Now, consider this two dimensional array

example341=Table[i*8+j,{i,0,4},{j,0,7}] ;
Grid[example341]

example341[[3,7]]

Manipulate[
ex341grdisp=ex341gr;
ex341grdisp[[i+1,j+1]]=Item[Style[example341[[i,j]],19,Bold,White]
,Background->Hue[0.,1,1]];
Grid[{{Grid[{{Style["arrayname[["<>ToString[i]<>","<>ToString[j]<>"]]"
,20,FontFamily->"Times New Roman"]}
,{Item[Style[example341[[i,j]],28,FontFamily->"Calibri",Bold,White]
,Background->Red]}}
,Frame->All
]
,Grid[ex341grdisp
,Frame-> All,BaseStyle->{20,FontFamily->"Calibri"}
,Background->{Join[{Hue[0.77,0.5,1]},Table[If[j==n,Hue[0.05,0.5,1],],{n,1,col+1}]]
,Join[{Hue[0.47,0.5,1]},Table[If[i==m,Hue[0.3,0.5,1],],{m,1,row+1}]]}]}}]
,{i,1,5,1},{j,1,8,1}
,Initialization:>{
example341=RandomInteger[{0,50},{5,8}] ;
{row,col}=Dimensions[example341];
ex341gr=MapThread[Prepend,{Join[{Range[col]},example341]
,Join[{Item[Style["i/j",Bold,White,FontFamily->"Arial"]
,Background->Black]},Range[row]]}];
}]