CPSC 215

February (1^st), 2002

C. Jacob / S. Kaufmann

Lists

Manipulating Lists (continued)

Flattening Lists ⟵

Or we can use the function Flatten, which “flattens out” a nested list into a one-dimensional one.

{a} // TreeForm

myList = {a, {{b, c}, d}, {e, {f, {{g}}}}};

TreeForm[myList]

Flatten[myList]

Flatten[myList, 1]

Flatten[myList, 2]

Flatten[myList, 3]

Flatten[myList, 4]

Flattening Expressions

myExpr = f[a, f[f[b, c], d], f[e, f[t, f[f[a], b]]]];

myExpr // TreeForm

Flatten[myExpr]

Flatten[myExpr, 1]

Flatten[myExpr, 2]

Flatten[myExpr, 3]

Flatten[myExpr, ∞]

Selecting List Elements through Patterns

Position gives the position(s) of a pattern; the corresponding elements can be extracted with Extract.

myList = {(a^2), b, b, c, (d^3), g[b], f[e, g[a, (c^2)]]}

Position[myList, b]

Extract[myList, %]

Position[myList, _^2]

Extract[myList, %]

Cases extracts the matching patterns:

\(Cases[myList, _\^3]\)

Cases[myList, _[_]]

Cases[myList, _[__]]

Select tests the elements of a list for properties. The list must be given together with a function, which returns True for the desired elements.

myTest[x_] = (x > 10) && (x < 50)

Select[Table[i^2, {i, 10}], myTest]

Multidimensional Lists

Table can also create multidimensional lists.

Here is a simple example to create a matrix (({{(Subscript[a, 1, 1]), (Subscript[a, 1, 2])}, {(Subscript[a, 2, 1]), (Subscript[a, 2, 2])}}))

\(Table[a\_{i, j}, {i, 1, 2}, {j, 1, 2}] // MatrixForm\)

And a little bit of re-formatting gives us the desired output format:

% /. {(Subscript[a, x])_ :> (Subscript[a, Sequence @@ x])} // MatrixForm

Creating a multiplication table:

(multTable = Table[i*j, {i, 1, 12}, {j, 1, 12}]) // 
      MatrixForm

ListPlot3D[multTable];

ListDensityPlot[multTable];

Creating a power table:

(powTable = Table[(i^j), {i, 1, 8}, {j, 1, 8}]) // 
      MatrixForm

ListPlot3D[powTable];

ListDensityPlot[powTable];

(modTable = Table[Mod[i, j], {i, 10, 20}, {j, 10, 20}]) // 
      MatrixForm

ListDensityPlot[modTable];

ListDensityPlot[Table[Mod[i, j], {i, 1, 100}, {j, 1, 100}], 
        ColorFunction -> Hue];