The code shows the expected behavior:
In the first iteration xvals is empty, than length(xvals)+1 is 1. After setting xvals to a [2, 1] vector, its length is 2, so length(xvals)+1 is 3.
length() is a dangerous command, which causes bugs frequently. If chooses the longest dimension automagfically. If you want to measure the size of the 2nd dimension, use size(xvals, 2) instead.