What you are running into are two quirks of how axes behaves.
First, when applying the tick labels, MATLAB starts at the first tick and uses the first label, at the second tick it uses the second label, etc. If it runs out of tick labels but has more ticks that need labels, it starts back at the first label. For example, if you have 5 ticks and 3 tick labels, the first and second tick label will be reused for the 4th and 5th ticks.
In this case, you are using the following code to set the x-ticks:
This is setting 1001 ticks on the axes, and by setting the ticks manually, you are preventing an automatic calculation which may move the ticks to a new location (or change the number of ticks).
The second quirk you are encountering is that when the tick labels are being automatically generated, MATLAB only generates labels for ticks that are on the screen. The code you are using to set the tick labels is:
The first time that command is called, there are only three ticks within the x-limits, so the value of XTickLabel has only three elements. Then you are setting the XTickLabel property, effectivelty locking-in the three tick labels and disabling automatic label calculation for all subsequent loops.
At this point, you have 1001 ticks and three labels, so MATLAB assigns the first label to the first tick, the second label to the second tick, the third label to the third tick, the first label to the fourth tick, the second label to the fifth tick, etc. Hence the repeating labels.
One more thing to note is that calling cla does not reset the tick values or labels, so the settings from the previous loop are being reused for the second and subsequent loops.
There are a couple solutions to this:
- One option is to make sure to specifically set one label per tick. You can do this either by setting the XTickLabel property with the labels you want explicitly (you can use numeric values, which will be converted to strings). Better yet, as Aaron suggested, is to use the xticklabels command (instead of setting the XTickLabels property). The command will check if there are more ticks than tick labels, and will pad the labels with empty labels if needed, to avoid the problem of repeating tick labels.
- It is not clear why you are setting the XTickLabel property to be equal to itself, so you could remove that line entirely. This will maintain automatic tick labeling, and will also resolve this issue.
- Set XTickLabelMode back to 'auto' at the beginning of your loop (you can also call xticklabel('auto')). This will reset the automatically calculated tick labels based on the new axes limits.
- If your goal is to change the formatting used for the tick labels, you may consider setting the XAxis.TickLabelFormat property to control the formatting of the tick labels, rather than hard-coding the labels themselves. You can also use the shortcut xtickformat command.