1
$\begingroup$

How can I intersperse strings among variables to create a table with labels for each entry. A simple example of what I tried to do would be a table of the value of a function $f(x)$ and the value of $x$. For example:

Table[{"x=" x, "f[x]=" f}, {x, 0, 1, .1}] // TableForm

What I would like to obtain:

x=0   f=f[0]
x=0.1 f=f[0.1]
x=0.2 f=f[0.2]
...

But, of course, my code didn't produce that.

$\endgroup$
  • 2
    $\begingroup$ Table[StringTemplate["x=`` f[x]=f[``]"][x, x], {x, 0, 1, .1}] // TableForm You can also use StringJoin if you first apply ToString to the numeric values. $\endgroup$ – C. E. Jun 8 '17 at 22:19
1
$\begingroup$

m_goldberg's answer is good for small outputs, but you have to consider that internally, Mathematica will create very complex front end structures to display lots of "boxes" - strings mixed with integers, formatted, each to have their paddings and frames and margins, etc. In a large enough output or long enough notebook, this can really add up. Alternatively, use ToString to convert numbers to strings (use NumberForm and others to format the number, if you'd like, and IntegerString to convert to other systems, such as Binary, or Roman numerals, etc). Use <> instead of + to join strings.

Table[{"x="<>ToString[x], "f[x]="<>ToString[f[x]]}, {x, 0, 1, .1}] // TableForm

...produces the output you want

$\endgroup$
  • $\begingroup$ Thanks for the simple and effective solution! $\endgroup$ – Pierre Jun 9 '17 at 14:02
1
$\begingroup$

Row is your friend is a situation like this.

Table[{Row[{"x = ", x}], Row[{"f = f[", x, "]"}]}, {x, 0, 1, .1}] // TableForm

table

$\endgroup$
  • $\begingroup$ Great answer! While it does the trick, I found @Gregory 's answer simpler to implement. Thanks! $\endgroup$ – Pierre Jun 9 '17 at 14:01

Not the answer you're looking for? Browse other questions tagged or ask your own question.