Wednesday, June 3, 2015

Two Ways to Add Line Numbers to a Table

Often we'd like to add line numbers to a table of data. Here's a simple method using the formula for distance traveled in meters by a falling body near the earth's surface (0.5 x 9.8 m/s2).

Using Table with Iterator

It is easy to see that the lone iterator "i" simply supplies the line numbers, indicating 1 to 20 seconds, for TableForm.

Table[{i,4.9 i^2},{i,20}]//TableForm




















Here's a fancier version with headings. The first "None" in TableHeadings is for row labels, which we don't need since the Table iterator provided them, while the second set of values are the column headings. TableForm doesn't provide for a title, but we can add one with Labeled. A "\n" creates a line break and we need Style to center the title.


Table[{i,4.9 i^2},{i,20}]//TableForm[#,TableHeadings->{None,{"Seconds","Meters"}}]&//Labeled[#,"Distance Traveled in 20 Seconds\nof Free Fall Near the Earth's Surface\n",Top]&//Style[#,TextAlignment->Center]&





















Using MapIndexed

Here the formula for distance in feet is expressed in pure Function shorthand, which is then mapped onto the integers from 1 to 20 generated by Range, representing 20 seconds of free fall from v0 = 0. A pure Function is the fast way to write a one-off function that you don't intend to re-use.

MapIndexed adds the index to the expression as a suffix, so we need to Map Reverse on to each data item that will be a row in the table.

MapIndexed[{16#^2,#2}&,Range@2]

Out[53]= {{16,{1}},{64,{2}}}

Last we apply TableForm.

MapIndexed[{4.9 #^2, #2} &, Range@20] // Reverse /@ # & // TableForm







No comments:

Post a Comment