This happens because the tick labels have to match the ticks themselves. In the example you gave with N = 16;
and x = 1:N;
, MATLAB automatically makes the following XTick
s (on your and my machines, at least):
>> xticks = get(gca,'xtick')
xticks =
0 2 4 6 8 10 12 14 16 18
>> numel(xticks)
ans =
10
Just 10 ticks for the 16 different bars. Thus, when you run set(gca, 'XTickLabel', labels);
with labels = num2str(x', '%d');
(16 labels), it gives the second figure you showed with the wrong labels and ticks before/after the bars (at positions 0 and 18).
To set a tick label for each bar, you also need to set the ticks to match:
set(gca,'XTick',x) % this alone should be enough
set(gca,'XTickLabel',labels);
Then you will get the desired result:
For whatever reason, 16 seems to be the magic number at which MathWorks decided XTick
s should not be drawn for each bar, leaving it up to the user to set them if needed.