When you do the
then all of the items after index i "fall down" to occupy the missing space, so what was previously i+1 becomes located at i, what was at i+2 becomes located at i+1, and so on. You then fill in the empty slot at the end with an occurrence of "a", so the array maintains its length. However, when you increment "i", you fail to look at the value that "fell down" into the location "i".
You also have
elseif v ~= a
v = [v, zeros(1, i)];
end
This is testing the entire vector v for equality to a; the v ~= a part computes a logical vector. "elseif" considers the test to be true only if all of the members of the logical vector are true, equivalent to if you had tested
In the case where all of the v are different from a, you proceed to add a bunch of zeros on to the end of the existing v. The next loop through, if a is equal to 0, the test would fail because there would be some place for which v ~= 0 would fail, but if a was non-zero, then you would proceed to add even more zeros on to the end of v...
The instructions you were given about zeros are saying that you should test
if ~exist('a', 'var')
a = 0;
end
and otherwise do not do anything special about 0.
Best Answer