You are looking for the TableHeadings
option of TableForm
.
table = Table[i^2 + j*3, {i, 1, 3, .5}, {j, 1, 7, .5}];
rowHeaders = Range[1, 3, .5];
columnHeaders = Range[1, 7, .5];
{rowVar, columnVar} = {"i", "j"};
TableForm[table, TableHeadings -> {rowHeaders, columnHeaders}]
If you want to show the row and column variable names then you have to pad the data with empty strings to make room for the extra labels.
TableForm[
ArrayPad[table, {{1, 0}, {1, 0}}, ""],
TableHeadings -> {{rowVar}~Join~rowHeaders,
{columnVar}~Join~columnHeaders}
]
Note: Data should be left as data (Table
or List
); separate from presentation (TableForm
). That way you can choose to display it as a TableForm
, MatrixForm
, or easily work with the data the later on. In particular
(* Bad practice *)
n = Table[i^2 + j*3, {i, 3}, {j, 7}] // TableForm;
(* Fail *)
TableForm[n, TableHeadings -> {Range@3, Range@7}]
Edit: There used to be an answer by @kguler which addresses exporting the headers to Excel by prepending the headers to the data. This uses the same method, perhaps in a more easily readable format.
formatTable[table_, {rowHeaders_, columnHeaders_}, {rowVar_, columnVar_}] :=
table //
ArrayPad[#, {{1, 0}, {1, 0}}, ""] & //
Prepend[#, {columnVar}~Join~columnHeaders] & //
Transpose //
Prepend[#, {"", rowVar}~Join~rowHeaders] & //
Transpose;
Export["stuck.xls", formatTable[table, {rowHeaders, columnHeaders}, {rowVar, columnVar}]]