Strings in mpost for loop

69 views Asked by At

I'm trying to do the following:

xN := 200;
topp:= 3;
bott := -3;
spac := 20;

% draw number line
draw (0,0)--(xN,0);

last := 3;

% draw 4 tick marks from left side
for i := 0 upto last:
    draw (spac*i,topp)..(spac*i,bott);
endfor;

% label tick marks accordingly
for i := 0 upto last:
    label.bot(btex $x_{i}$ etex, (i*spac,bott));
endfor;

The goal is for the left tick to be x_0, the next one to be x_1, and so on. But since I'm labeling in a tex environment, it's not using the i in the label command as the variable but rather just a letter. The result is that every tick mark is labeled at "x_{i}". Sorry if this is unclear, this is my first attempt at using metapost and I figured there has to be a way to do this using a loop rather than brute forcing it.

1

There are 1 answers

0
Gassa On

As in a similar question: add an input tex; line to include the TEX macro, and then change

label.bot(btex $x_{i}$ etex, (i*spac,bott));

into the following:

label.bot(TEX ("$x_" & decimal (i) & "$"), (i*spac,bott));

This way, the value of i is converted into decimal representation, then a string $x_0$ or $x_1$ etc. is constructed, and then the TEX macro compiles it into a pretty-looking label.