x(end+1) = newElem
is a bit more robust.
x = [x newElem]
will only work if x
is a row-vector, if it is a column vector x = [x; newElem]
should be used. x(end+1) = newElem
, however, works for both row- and column-vectors.
In general though, growing vectors should be avoided. If you do this a lot, it might bring your code down to a crawl. Think about it: growing an array involves allocating new space, copying everything over, adding the new element, and cleaning up the old mess...Quite a waste of time if you knew the correct size beforehand :)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…